Spaces:
Runtime error
Runtime error
gmftbyGMFTBY
commited on
Commit
•
8366b03
1
Parent(s):
c9d5d84
update
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- LICENSE +201 -0
- README.md +195 -13
- app.py +228 -0
- assets/audios/bird_audio.wav +0 -0
- assets/audios/car_audio.wav +0 -0
- assets/audios/dog_audio.wav +0 -0
- assets/images/bird_image.jpg +0 -0
- assets/images/car_image.jpg +0 -0
- assets/images/dog_image.jpg +0 -0
- assets/thermals/190662.jpg +0 -0
- assets/thermals/210009.jpg +0 -0
- assets/videos/a.mp4 +0 -0
- config/__init__.py +37 -0
- config/base.yaml +15 -0
- config/openllama_peft.yaml +22 -0
- data/empty.txt +1 -0
- datasets/__init__.py +40 -0
- datasets/samplers.py +166 -0
- datasets/sft_dataset.py +65 -0
- dsconfig/openllama_peft_stage_1.json +54 -0
- header.py +35 -0
- model/ImageBind/CODE_OF_CONDUCT.md +80 -0
- model/ImageBind/CONTRIBUTING.md +31 -0
- model/ImageBind/LICENSE +437 -0
- model/ImageBind/README.md +155 -0
- model/ImageBind/__init__.py +2 -0
- model/ImageBind/__pycache__/__init__.cpython-39.pyc +0 -0
- model/ImageBind/__pycache__/data.cpython-39.pyc +0 -0
- model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz +3 -0
- model/ImageBind/data.py +372 -0
- model/ImageBind/model_card.md +94 -0
- model/ImageBind/models/__init__.py +0 -0
- model/ImageBind/models/__pycache__/__init__.cpython-39.pyc +0 -0
- model/ImageBind/models/__pycache__/helpers.cpython-39.pyc +0 -0
- model/ImageBind/models/__pycache__/imagebind_model.cpython-39.pyc +0 -0
- model/ImageBind/models/__pycache__/multimodal_preprocessors.cpython-39.pyc +0 -0
- model/ImageBind/models/__pycache__/transformer.cpython-39.pyc +0 -0
- model/ImageBind/models/helpers.py +141 -0
- model/ImageBind/models/imagebind_model.py +521 -0
- model/ImageBind/models/multimodal_preprocessors.py +687 -0
- model/ImageBind/models/transformer.py +284 -0
- model/ImageBind/requirements.txt +10 -0
- model/__init__.py +9 -0
- model/agent.py +68 -0
- model/modeling_llama.py +755 -0
- model/openllama.py +292 -0
- pretrained_ckpt/README.md +78 -0
- pretrained_ckpt/imagebind_ckpt/empty.txt +1 -0
- pretrained_ckpt/pandagpt_ckpt/13b/empty.txt +1 -0
.gitattributes
CHANGED
@@ -32,3 +32,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
+
pretrained_ckpt/pandagpt_ckpt/7b/pytorch_model.pt filter=lfs diff=lfs merge=lfs -text
|
36 |
+
model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [yyyy] [name of copyright owner]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
README.md
CHANGED
@@ -1,13 +1,195 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<p align="center" width="100%">
|
2 |
+
<img src="./pandagpt.png" alt="PandaGPT-4" style="width: 40%; min-width: 300px; display: block; margin: auto;">
|
3 |
+
</p>
|
4 |
+
|
5 |
+
# PandaGPT: One Model To Instruction-Follow Them All
|
6 |
+
|
7 |
+
![Data License](https://img.shields.io/badge/Data%20License-CC%20By%20NC%204.0-red.svg)
|
8 |
+
![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)
|
9 |
+
![Model Weight License](https://img.shields.io/badge/Model_Weight%20License-CC%20By%20NC%204.0-red.svg)
|
10 |
+
![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)
|
11 |
+
|
12 |
+
|
13 |
+
[[Project Page](https://panda-gpt.github.io/)] [[Paper]()] [[Video]](https://www.youtube.com/watch?v=96XgdQle7EY)[[Demo]()] [[Data](https://github.com/yxuansu/PandaGPT/blob/main/README.md#31-data-preparation)] [[Model](https://github.com/yxuansu/PandaGPT/blob/main/README.md#24-prepare-delta-weights-of-pandagpt)]
|
14 |
+
|
15 |
+
****
|
16 |
+
|
17 |
+
<span id='all_catelogue'/>
|
18 |
+
|
19 |
+
## Catalogue:
|
20 |
+
* <a href='#introduction'>1. Introduction</a>
|
21 |
+
* <a href='#environment'>2. Running PandaGPT Demo</a>
|
22 |
+
* <a href='#install_environment'>2.1. Environment Installation</a>
|
23 |
+
* <a href='#download_imagebind_model'>2.2. Prepare ImageBind Checkpoint</a>
|
24 |
+
* <a href='#download_vicuna_model'>2.3. Prepare Vicuna Checkpoint</a>
|
25 |
+
* <a href='#download_pandagpt'>2.4. Prepare Delta Weights of PandaGPT</a>
|
26 |
+
* <a href='#running_demo'>2.5. Deploying Demo</a>
|
27 |
+
* <a href='#train_pandagpt'>3. Train Your Own PandaGPT</a>
|
28 |
+
* <a href='#data_preparation'>3.1. Data Preparation</a>
|
29 |
+
* <a href='#training_configurations'>3.2. Training Configurations</a>
|
30 |
+
* <a href='#model_training'>3.3. Training PandaGPT</a>
|
31 |
+
* <a href='#license'>Usage and License Notices</a>
|
32 |
+
* <a href='#acknowledgments'>Acknowledgments</a>
|
33 |
+
|
34 |
+
****
|
35 |
+
|
36 |
+
<span id='introduction'/>
|
37 |
+
|
38 |
+
### 1. Introduction: <a href='#all_catelogue'>[Back to Top]</a>
|
39 |
+
|
40 |
+
<p align="center" width="100%">
|
41 |
+
<img src="./PandaGPT.png" alt="PandaGPT-4" style="width: 80%; min-width: 300px; display: block; margin: auto;">
|
42 |
+
</p>
|
43 |
+
|
44 |
+
PandaGPT is the first foundation model capable of instruction-following data across six modalities, without the need of explicit supervision. It demonstrates a diverse set of multimodal capabilities such as complex understanding/reasoning, knowledge-grounded description, and multi-turn conversation.
|
45 |
+
|
46 |
+
|
47 |
+
****
|
48 |
+
|
49 |
+
<span id='environment'/>
|
50 |
+
|
51 |
+
### 2. Running PandaGPT Demo: <a href='#all_catelogue'>[Back to Top]</a>
|
52 |
+
|
53 |
+
<span id='install_environment'/>
|
54 |
+
|
55 |
+
#### 2.1. Environment Installation:
|
56 |
+
To install the required environment, please run
|
57 |
+
```
|
58 |
+
pip install -r requirements.txt
|
59 |
+
```
|
60 |
+
|
61 |
+
Then install the Pytorch package with the correct cuda version, for example
|
62 |
+
```
|
63 |
+
pip install torch==1.13.1+cu117 -f https://download.pytorch.org/whl/torch/
|
64 |
+
```
|
65 |
+
|
66 |
+
<span id='download_imagebind_model'/>
|
67 |
+
|
68 |
+
#### 2.2. Prepare ImageBind Checkpoint:
|
69 |
+
You can download the pre-trained ImageBind model using [this link](https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth). After downloading, put the downloaded file (imagebind_huge.pth) in [[./pretrained_ckpt/imagebind_ckpt/]](./pretrained_ckpt/imagebind_ckpt/) directory.
|
70 |
+
|
71 |
+
<span id='download_vicuna_model'/>
|
72 |
+
|
73 |
+
#### 2.3. Prepare Vicuna Checkpoint:
|
74 |
+
To prepare the pre-trained Vicuna model, please follow the instructions provided [[here]](./pretrained_ckpt#1-prepare-vicuna-checkpoint).
|
75 |
+
|
76 |
+
|
77 |
+
<span id='download_pandagpt'/>
|
78 |
+
|
79 |
+
#### 2.4. Prepare Delta Weights of PandaGPT:
|
80 |
+
|
81 |
+
|**Base Language Model**|**Maximum Length**|**Huggingface Delta Weights Address**|
|
82 |
+
|:-------------:|:-------------:|:-------------:|
|
83 |
+
|Vicuna-7B (version 0)|512|[openllmplayground/pandagpt_7b_max_len_512](https://huggingface.co/openllmplayground/pandagpt_7b_max_len_512)|
|
84 |
+
|Vicuna-7B (version 0)|1024|[openllmplayground/pandagpt_7b_max_len_1024](https://huggingface.co/openllmplayground/pandagpt_7b_max_len_1024)|
|
85 |
+
|Vicuna-13B (version 0)|256|[openllmplayground/pandagpt_13b_max_len_256](https://huggingface.co/openllmplayground/pandagpt_13b_max_len_256)|
|
86 |
+
|Vicuna-13B (version 0)|400|[openllmplayground/pandagpt_13b_max_len_400](https://huggingface.co/openllmplayground/pandagpt_13b_max_len_400)|
|
87 |
+
|
88 |
+
We release the delta weights of PandaGPT trained with different strategies in the table above. After downloading, put the downloaded 7B/13B delta weights file (pytorch_model.pt) in the [[./pretrained_ckpt/pandagpt_ckpt/7b/]](./pretrained_ckpt/pandagpt_ckpt/7b/) or [[./pretrained_ckpt/pandagpt_ckpt/13b/]](./pretrained_ckpt/pandagpt_ckpt/13b/) directory. In our online demo, we use the `openllmplayground/pandagpt_7b_max_len_512` and `openllmplayground/pandagpt_13b_max_len_400` as our default models.
|
89 |
+
|
90 |
+
<span id='running_demo'/>
|
91 |
+
|
92 |
+
#### 2.5. Deploying Demo:
|
93 |
+
Upon completion of previous steps, you can run the demo as
|
94 |
+
```bash
|
95 |
+
cd ./code/
|
96 |
+
python web_demo.py
|
97 |
+
```
|
98 |
+
|
99 |
+
****
|
100 |
+
|
101 |
+
<span id='train_pandagpt'/>
|
102 |
+
|
103 |
+
### 3. Train Your Own PandaGPT: <a href='#all_catelogue'>[Back to Top]</a>
|
104 |
+
|
105 |
+
**Prerequisites:** Before training the model, making sure the environment is properly installed and the checkpoints of ImageBind and Vicuna are downloaded. You can refer to [here](https://github.com/yxuansu/PandaGPT#2-running-pandagpt-demo-back-to-top) for more information.
|
106 |
+
|
107 |
+
<span id='data_preparation'/>
|
108 |
+
|
109 |
+
#### 3.1. Data Preparation:
|
110 |
+
|
111 |
+
**Declaimer:** To ensure the reproducibility of our results, we have released our training datasets. The datasets must be used for research purpose only. The use of the datasets must comply with the licenses from original sources. These datasets may be taken down when requested by the original authors.
|
112 |
+
|
113 |
+
|**Training Task**|**Dataset Address**|
|
114 |
+
|:-------------:|:-------------:|
|
115 |
+
|Visual Instruction|[openllmplayground/pandagpt_visual_instruction_dataset](https://huggingface.co/datasets/openllmplayground/pandagpt_visual_instruction_dataset)|
|
116 |
+
|
117 |
+
After downloading, put the downloaded file and unzip them under the [[./data/]](./data/) directory.
|
118 |
+
|
119 |
+
> **** The directory should look like:
|
120 |
+
|
121 |
+
.
|
122 |
+
└── ./data/
|
123 |
+
├── pandagpt4_visual_instruction_data.json
|
124 |
+
└── /images/
|
125 |
+
├── 000000426538.jpg
|
126 |
+
├── 000000306060.jpg
|
127 |
+
└── ...
|
128 |
+
|
129 |
+
|
130 |
+
<span id='training_configurations'/>
|
131 |
+
|
132 |
+
#### 3.2 Training Configurations:
|
133 |
+
|
134 |
+
The table below show the training hyperparameters used in our experiments. The hyperparameters are selected based on the constrain of our computational resources, i.e. 8 x A100 (40G) GPUs.
|
135 |
+
|
136 |
+
|**Base Language Model**|**Training Task**|**Epoch Number**|**Batch Size**|**Learning Rate**|**Maximum Length**|
|
137 |
+
|:-------------:|:-------------:|:-------------:|:-------------:|:-------------:|:-------------:|
|
138 |
+
|7B|Visual Instruction|2|64|5e-4|1024|
|
139 |
+
|13B|Visual Instruction|2|64|5e-4|400|
|
140 |
+
|
141 |
+
|
142 |
+
|
143 |
+
<span id='model_training'/>
|
144 |
+
|
145 |
+
|
146 |
+
#### 3.3. Training PandaGPT:
|
147 |
+
|
148 |
+
To train PandaGPT, please run the following commands:
|
149 |
+
```yaml
|
150 |
+
cd ./code/scripts/
|
151 |
+
chmod +x train.sh
|
152 |
+
cd ..
|
153 |
+
./scripts/train.sh
|
154 |
+
```
|
155 |
+
|
156 |
+
The key arguments of the training script are as follows:
|
157 |
+
* `--data_path`: The data path for the json file `pandagpt4_visual_instruction_data.json`.
|
158 |
+
* `--image_root_path`: The root path for the downloaded images.
|
159 |
+
* `--imagebind_ckpt_path`: The path where saves the ImageBind checkpoint `imagebind_huge.pth`.
|
160 |
+
* `--vicuna_ckpt_path`: The directory that saves the pre-trained Vicuna checkpoints.
|
161 |
+
* `--max_tgt_len`: The maximum length of training instances.
|
162 |
+
* `--save_path`: The directory which saves the trained delta weights. This directory will be automatically created.
|
163 |
+
|
164 |
+
Note that the epoch number can be set in the `epochs` argument at [./code/config/openllama_peft.yaml](./code/config/openllama_peft.yaml) file. The `train_micro_batch_size_per_gpu` and `gradient_accumulation_steps` arguments in [./code/dsconfig/openllama_peft_stage_1.json](./code/dsconfig/openllama_peft_stage_1.json) should be set as `2` and `4` for 7B model, and set as `1` and `8` for 13B model.
|
165 |
+
|
166 |
+
****
|
167 |
+
|
168 |
+
<span id='license'/>
|
169 |
+
|
170 |
+
### Usage and License Notices:
|
171 |
+
|
172 |
+
PandaGPT is intended and licensed for research use only. The dataset is CC BY NC 4.0 (allowing only non-commercial use) and models trained using the dataset should not be used outside of research purposes. The delta weights are also CC BY NC 4.0 (allowing only non-commercial use).
|
173 |
+
|
174 |
+
|
175 |
+
****
|
176 |
+
|
177 |
+
<span id='acknowledgments'/>
|
178 |
+
|
179 |
+
### Acknowledgments:
|
180 |
+
|
181 |
+
|
182 |
+
This repo benefits from [OpenAlpaca](https://github.com/yxuansu/OpenAlpaca), [ImageBind](https://github.com/facebookresearch/ImageBind), [LLaVA](https://github.com/haotian-liu/LLaVA), and [MiniGPT-4](https://github.com/Vision-CAIR/MiniGPT-4). Thanks for their wonderful works!
|
183 |
+
|
184 |
+
|
185 |
+
|
186 |
+
|
187 |
+
|
188 |
+
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
|
193 |
+
|
194 |
+
|
195 |
+
|
app.py
ADDED
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModel, AutoTokenizer
|
2 |
+
import os
|
3 |
+
import ipdb
|
4 |
+
import gradio as gr
|
5 |
+
import mdtex2html
|
6 |
+
from model.openllama import OpenLLAMAPEFTModel
|
7 |
+
import torch
|
8 |
+
import json
|
9 |
+
|
10 |
+
# init the model
|
11 |
+
args = {
|
12 |
+
'model': 'openllama_peft',
|
13 |
+
'imagebind_ckpt_path': './pretrained_ckpt/imagebind_ckpt/',
|
14 |
+
'vicuna_ckpt_path': 'openllmplayground/vicuna_7b_v0',
|
15 |
+
'delta_ckpt_path': './pretrained_ckpt/pandagpt_ckpt/pytorch_model.pt',
|
16 |
+
'stage': 2,
|
17 |
+
'max_tgt_len': 128,
|
18 |
+
'lora_r': 32,
|
19 |
+
'lora_alpha': 32,
|
20 |
+
'lora_dropout': 0.1,
|
21 |
+
}
|
22 |
+
model = OpenLLAMAPEFTModel(**args)
|
23 |
+
delta_ckpt = torch.load(args['delta_ckpt_path'], map_location=torch.device('cpu'))
|
24 |
+
model.load_state_dict(delta_ckpt, strict=False)
|
25 |
+
model = model.eval().half().cuda()
|
26 |
+
print(f'[!] init the model over ...')
|
27 |
+
|
28 |
+
|
29 |
+
"""Override Chatbot.postprocess"""
|
30 |
+
|
31 |
+
|
32 |
+
def postprocess(self, y):
|
33 |
+
if y is None:
|
34 |
+
return []
|
35 |
+
for i, (message, response) in enumerate(y):
|
36 |
+
y[i] = (
|
37 |
+
None if message is None else mdtex2html.convert((message)),
|
38 |
+
None if response is None else mdtex2html.convert(response),
|
39 |
+
)
|
40 |
+
return y
|
41 |
+
|
42 |
+
|
43 |
+
gr.Chatbot.postprocess = postprocess
|
44 |
+
|
45 |
+
|
46 |
+
def parse_text(text):
|
47 |
+
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
|
48 |
+
lines = text.split("\n")
|
49 |
+
lines = [line for line in lines if line != ""]
|
50 |
+
count = 0
|
51 |
+
for i, line in enumerate(lines):
|
52 |
+
if "```" in line:
|
53 |
+
count += 1
|
54 |
+
items = line.split('`')
|
55 |
+
if count % 2 == 1:
|
56 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
57 |
+
else:
|
58 |
+
lines[i] = f'<br></code></pre>'
|
59 |
+
else:
|
60 |
+
if i > 0:
|
61 |
+
if count % 2 == 1:
|
62 |
+
line = line.replace("`", "\`")
|
63 |
+
line = line.replace("<", "<")
|
64 |
+
line = line.replace(">", ">")
|
65 |
+
line = line.replace(" ", " ")
|
66 |
+
line = line.replace("*", "*")
|
67 |
+
line = line.replace("_", "_")
|
68 |
+
line = line.replace("-", "-")
|
69 |
+
line = line.replace(".", ".")
|
70 |
+
line = line.replace("!", "!")
|
71 |
+
line = line.replace("(", "(")
|
72 |
+
line = line.replace(")", ")")
|
73 |
+
line = line.replace("$", "$")
|
74 |
+
lines[i] = "<br>"+line
|
75 |
+
text = "".join(lines)
|
76 |
+
return text
|
77 |
+
|
78 |
+
|
79 |
+
def predict(
|
80 |
+
input,
|
81 |
+
image_path,
|
82 |
+
audio_path,
|
83 |
+
video_path,
|
84 |
+
thermal_path,
|
85 |
+
chatbot,
|
86 |
+
max_length,
|
87 |
+
top_p,
|
88 |
+
temperature,
|
89 |
+
history,
|
90 |
+
modality_cache,
|
91 |
+
):
|
92 |
+
if image_path is None and audio_path is None and video_path is None and thermal_path is None:
|
93 |
+
return [(input, "There is no image/audio/video provided. Please upload the file to start a conversation.")]
|
94 |
+
else:
|
95 |
+
print(f'[!] image path: {image_path}\n[!] audio path: {audio_path}\n[!] video path: {video_path}\n[!] thermal pah: {thermal_path}')
|
96 |
+
# prepare the prompt
|
97 |
+
|
98 |
+
prompt_text = ''
|
99 |
+
for idx, (q, a) in enumerate(history):
|
100 |
+
if idx == 0:
|
101 |
+
prompt_text += f'{q}\n### Assistant: {a}\n###'
|
102 |
+
else:
|
103 |
+
prompt_text += f' Human: {q}\n### Assistant: {a}\n###'
|
104 |
+
if len(history) == 0:
|
105 |
+
prompt_text += f'{input}'
|
106 |
+
else:
|
107 |
+
prompt_text += f' Human: {input}'
|
108 |
+
|
109 |
+
response = model.generate({
|
110 |
+
'prompt': prompt_text,
|
111 |
+
'image_paths': [image_path] if image_path else [],
|
112 |
+
'audio_paths': [audio_path] if audio_path else [],
|
113 |
+
'video_paths': [video_path] if video_path else [],
|
114 |
+
'thermal_paths': [thermal_path] if thermal_path else [],
|
115 |
+
'top_p': top_p,
|
116 |
+
'temperature': temperature,
|
117 |
+
'max_tgt_len': max_length,
|
118 |
+
'modality_embeds': modality_cache
|
119 |
+
})
|
120 |
+
chatbot.append((parse_text(input), parse_text(response)))
|
121 |
+
history.append((input, response))
|
122 |
+
return chatbot, history, modality_cache
|
123 |
+
|
124 |
+
|
125 |
+
def reset_user_input():
|
126 |
+
return gr.update(value='')
|
127 |
+
|
128 |
+
|
129 |
+
def reset_state():
|
130 |
+
return None, None, None, None, [], [], []
|
131 |
+
|
132 |
+
|
133 |
+
with gr.Blocks() as demo:
|
134 |
+
gr.HTML("""<h1 align="center">PandaGPT</h1>""")
|
135 |
+
|
136 |
+
with gr.Row(scale=4):
|
137 |
+
with gr.Column(scale=2):
|
138 |
+
image_path = gr.Image(type="filepath", label="Image", value=None)
|
139 |
+
|
140 |
+
gr.Examples(
|
141 |
+
[
|
142 |
+
os.path.join(os.path.dirname(__file__), "/assets/images/bird_image.jpg"),
|
143 |
+
os.path.join(os.path.dirname(__file__), "/assets/images/dog_image.jpg"),
|
144 |
+
os.path.join(os.path.dirname(__file__), "/assets/images/car_image.jpg"),
|
145 |
+
],
|
146 |
+
image_path
|
147 |
+
)
|
148 |
+
with gr.Column(scale=2):
|
149 |
+
audio_path = gr.Audio(type="filepath", label="Audio", value=None)
|
150 |
+
gr.Examples(
|
151 |
+
[
|
152 |
+
os.path.join(os.path.dirname(__file__), "/assets/audios/bird_audio.wav"),
|
153 |
+
os.path.join(os.path.dirname(__file__), "/assets/audios/dog_audio.wav"),
|
154 |
+
os.path.join(os.path.dirname(__file__), "/assets/audios/car_audio.wav"),
|
155 |
+
],
|
156 |
+
audio_path
|
157 |
+
)
|
158 |
+
with gr.Row(scale=4):
|
159 |
+
with gr.Column(scale=2):
|
160 |
+
video_path = gr.Video(type='file', label="Video")
|
161 |
+
|
162 |
+
gr.Examples(
|
163 |
+
[
|
164 |
+
os.path.join(os.path.dirname(__file__), "/assets/videos/world.mp4"),
|
165 |
+
os.path.join(os.path.dirname(__file__), "/assets/videos/a.mp4"),
|
166 |
+
],
|
167 |
+
video_path
|
168 |
+
)
|
169 |
+
with gr.Column(scale=2):
|
170 |
+
thermal_path = gr.Image(type="filepath", label="Thermal Image", value=None)
|
171 |
+
|
172 |
+
gr.Examples(
|
173 |
+
[
|
174 |
+
os.path.join(os.path.dirname(__file__), "/assets/thermals/190662.jpg"),
|
175 |
+
os.path.join(os.path.dirname(__file__), "/assets/thermals/210009.jpg"),
|
176 |
+
],
|
177 |
+
thermal_path
|
178 |
+
)
|
179 |
+
|
180 |
+
chatbot = gr.Chatbot()
|
181 |
+
with gr.Row():
|
182 |
+
with gr.Column(scale=4):
|
183 |
+
with gr.Column(scale=12):
|
184 |
+
user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10).style(container=False)
|
185 |
+
with gr.Column(min_width=32, scale=1):
|
186 |
+
submitBtn = gr.Button("Submit", variant="primary")
|
187 |
+
with gr.Column(scale=1):
|
188 |
+
emptyBtn = gr.Button("Clear History")
|
189 |
+
max_length = gr.Slider(0, 512, value=128, step=1.0, label="Maximum length", interactive=True)
|
190 |
+
top_p = gr.Slider(0, 1, value=0.4, step=0.01, label="Top P", interactive=True)
|
191 |
+
temperature = gr.Slider(0, 1, value=0.8, step=0.01, label="Temperature", interactive=True)
|
192 |
+
|
193 |
+
history = gr.State([])
|
194 |
+
modality_cache = gr.State([])
|
195 |
+
|
196 |
+
submitBtn.click(
|
197 |
+
predict, [
|
198 |
+
user_input,
|
199 |
+
image_path,
|
200 |
+
audio_path,
|
201 |
+
video_path,
|
202 |
+
thermal_path,
|
203 |
+
chatbot,
|
204 |
+
max_length,
|
205 |
+
top_p,
|
206 |
+
temperature,
|
207 |
+
history,
|
208 |
+
modality_cache,
|
209 |
+
], [
|
210 |
+
chatbot,
|
211 |
+
history,
|
212 |
+
modality_cache
|
213 |
+
],
|
214 |
+
show_progress=True
|
215 |
+
)
|
216 |
+
|
217 |
+
submitBtn.click(reset_user_input, [], [user_input])
|
218 |
+
emptyBtn.click(reset_state, outputs=[
|
219 |
+
image_path,
|
220 |
+
audio_path,
|
221 |
+
video_path,
|
222 |
+
thermal_path,
|
223 |
+
chatbot,
|
224 |
+
history,
|
225 |
+
modality_cache
|
226 |
+
], show_progress=True)
|
227 |
+
|
228 |
+
demo.queue().launch(share=False, inbrowser=True, server_name='0.0.0.0', server_port=24000)
|
assets/audios/bird_audio.wav
ADDED
Binary file (882 kB). View file
|
|
assets/audios/car_audio.wav
ADDED
Binary file (441 kB). View file
|
|
assets/audios/dog_audio.wav
ADDED
Binary file (461 kB). View file
|
|
assets/images/bird_image.jpg
ADDED
assets/images/car_image.jpg
ADDED
assets/images/dog_image.jpg
ADDED
assets/thermals/190662.jpg
ADDED
assets/thermals/210009.jpg
ADDED
assets/videos/a.mp4
ADDED
Binary file (130 kB). View file
|
|
config/__init__.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import yaml
|
2 |
+
|
3 |
+
def load_model_config(model, mode):
|
4 |
+
# load special config for each model
|
5 |
+
config_path = f'config/{model}.yaml'
|
6 |
+
print(f'[!] load configuration from {config_path}')
|
7 |
+
with open(config_path) as f:
|
8 |
+
configuration = yaml.load(f, Loader=yaml.FullLoader)
|
9 |
+
new_config = {}
|
10 |
+
for key, value in configuration.items():
|
11 |
+
if key in ['train', 'test', 'validation']:
|
12 |
+
if mode == key:
|
13 |
+
new_config.update(value)
|
14 |
+
else:
|
15 |
+
new_config[key] = value
|
16 |
+
configuration = new_config
|
17 |
+
return configuration
|
18 |
+
|
19 |
+
def load_config(args):
|
20 |
+
'''the configuration of each model can rewrite the base configuration'''
|
21 |
+
# base config
|
22 |
+
base_configuration = load_base_config()
|
23 |
+
|
24 |
+
# load one model config
|
25 |
+
configuration = load_model_config(args['model'], args['mode'])
|
26 |
+
|
27 |
+
# update and append the special config for base config
|
28 |
+
base_configuration.update(configuration)
|
29 |
+
configuration = base_configuration
|
30 |
+
return configuration
|
31 |
+
|
32 |
+
def load_base_config():
|
33 |
+
config_path = f'config/base.yaml'
|
34 |
+
with open(config_path) as f:
|
35 |
+
configuration = yaml.load(f, Loader=yaml.FullLoader)
|
36 |
+
print(f'[!] load base configuration: {config_path}')
|
37 |
+
return configuration
|
config/base.yaml
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
models:
|
2 |
+
openllama:
|
3 |
+
model_name: OpenLLAMAModel
|
4 |
+
agent_name: DeepSpeedAgent
|
5 |
+
stage1_train_dataset: SupervisedDataset
|
6 |
+
test_dataset: SelfInstructTestDataset
|
7 |
+
openllama_peft:
|
8 |
+
model_name: OpenLLAMAPEFTModel
|
9 |
+
agent_name: DeepSpeedAgent
|
10 |
+
stage1_train_dataset: SupervisedDataset
|
11 |
+
test_dataset: SelfInstructTestDataset
|
12 |
+
|
13 |
+
# ========= Global configuration ========== #
|
14 |
+
logging_step: 5
|
15 |
+
# ========= Global configuration ========== #
|
config/openllama_peft.yaml
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# generation hyper-parameters
|
2 |
+
max_len: 512
|
3 |
+
penalty_alpha: 0.6
|
4 |
+
top_k: 10
|
5 |
+
top_p: 0.7
|
6 |
+
random_prefix_len: 5
|
7 |
+
sample_num: 2
|
8 |
+
decoding_method: sampling
|
9 |
+
generate_len: 512
|
10 |
+
|
11 |
+
# lora hyper-parameters
|
12 |
+
lora_r: 32
|
13 |
+
lora_alpha: 32
|
14 |
+
lora_dropout: 0.1
|
15 |
+
|
16 |
+
# some train configuration, more can be found under dsconfig folder
|
17 |
+
train:
|
18 |
+
seed: 0
|
19 |
+
warmup_rate: 0.1
|
20 |
+
epochs: 2
|
21 |
+
max_length: 1024
|
22 |
+
max_shard_size: 10GB
|
data/empty.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
empty text
|
datasets/__init__.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from header import *
|
2 |
+
from .samplers import DistributedBatchSampler
|
3 |
+
from .sft_dataset import *
|
4 |
+
|
5 |
+
'''
|
6 |
+
def get_tokenizer(model):
|
7 |
+
tokenizer = LlamaTokenizer.from_pretrained(model)
|
8 |
+
tokenizer.bos_token_id, tokenizer.eos_token_id = 1, 2
|
9 |
+
tokenizer.pad_token = tokenizer.eos_token
|
10 |
+
return tokenizer
|
11 |
+
'''
|
12 |
+
|
13 |
+
def load_sft_dataset(args):
|
14 |
+
'''
|
15 |
+
tokenizer = get_tokenizer(args['model_path'])
|
16 |
+
dataset_name = args['models'][args['model']]['stage1_train_dataset'] # SupervisedDataset, str
|
17 |
+
data_path = args["data_path"]
|
18 |
+
data = globals()[dataset_name](data_path, tokenizer, args['max_length']) #SupervisedDataset
|
19 |
+
'''
|
20 |
+
data = SupervisedDataset(args['data_path'], args['image_root_path'])
|
21 |
+
|
22 |
+
sampler = torch.utils.data.RandomSampler(data)
|
23 |
+
world_size = torch.distributed.get_world_size()
|
24 |
+
rank = torch.distributed.get_rank()
|
25 |
+
batch_size = args['world_size'] * args['dschf'].config['train_micro_batch_size_per_gpu']
|
26 |
+
batch_sampler = DistributedBatchSampler(
|
27 |
+
sampler,
|
28 |
+
batch_size,
|
29 |
+
True,
|
30 |
+
rank,
|
31 |
+
world_size
|
32 |
+
)
|
33 |
+
iter_ = DataLoader(
|
34 |
+
data,
|
35 |
+
batch_sampler=batch_sampler,
|
36 |
+
num_workers=1,
|
37 |
+
collate_fn=data.collate,
|
38 |
+
pin_memory=True
|
39 |
+
)
|
40 |
+
return data, iter_, sampler
|
datasets/samplers.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""batch samplers that work with either random or sequential data samplers"""
|
16 |
+
import math
|
17 |
+
import os
|
18 |
+
import sys
|
19 |
+
|
20 |
+
import torch
|
21 |
+
from torch.utils import data
|
22 |
+
import numpy as np
|
23 |
+
|
24 |
+
|
25 |
+
class RandomSampler(data.sampler.Sampler):
|
26 |
+
r"""
|
27 |
+
Based off of pytorch RandomSampler and DistributedSampler. Essentially a RandomSampler,
|
28 |
+
but this class lets the user set an epoch like DistributedSampler
|
29 |
+
Samples elements randomly. If without replacement, then sample from a shuffled dataset.
|
30 |
+
If with replacement, then user can specify ``num_samples`` to draw.
|
31 |
+
Arguments:
|
32 |
+
data_source (Dataset): dataset to sample from
|
33 |
+
num_samples (int): number of samples to draw, default=len(dataset)
|
34 |
+
replacement (bool): samples are drawn with replacement if ``True``, default=False
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __init__(self, data_source, replacement=False, num_samples=None):
|
38 |
+
super(RandomSampler, self).__init__(data_source)
|
39 |
+
self.data_source = data_source
|
40 |
+
self.replacement = replacement
|
41 |
+
self._num_samples = num_samples
|
42 |
+
self.epoch = -1
|
43 |
+
|
44 |
+
if self._num_samples is not None and replacement is False:
|
45 |
+
raise ValueError("With replacement=False, num_samples should not be specified, "
|
46 |
+
"since a random permute will be performed.")
|
47 |
+
|
48 |
+
if not isinstance(self.num_samples, int) or self.num_samples <= 0:
|
49 |
+
raise ValueError("num_samples should be a positive integer "
|
50 |
+
"value, but got num_samples={}".format(self.num_samples))
|
51 |
+
if not isinstance(self.replacement, bool):
|
52 |
+
raise ValueError("replacement should be a boolean value, but got "
|
53 |
+
"replacement={}".format(self.replacement))
|
54 |
+
|
55 |
+
@property
|
56 |
+
def num_samples(self):
|
57 |
+
# dataset size might change at runtime
|
58 |
+
if self._num_samples is None:
|
59 |
+
return len(self.data_source)
|
60 |
+
return self._num_samples
|
61 |
+
|
62 |
+
def __iter__(self):
|
63 |
+
n = len(self.data_source)
|
64 |
+
g = torch.Generator()
|
65 |
+
if self.epoch >= 0:
|
66 |
+
g.manual_seed(self.epoch)
|
67 |
+
if self.replacement:
|
68 |
+
for _ in range(self.num_samples // 32):
|
69 |
+
yield from torch.randint(high=n, size=(32,), dtype=torch.int64, generator=g).tolist()
|
70 |
+
yield from torch.randint(high=n, size=(self.num_samples % 32,), dtype=torch.int64,
|
71 |
+
generator=g).tolist()
|
72 |
+
else:
|
73 |
+
yield from torch.randperm(n, generator=self.generator).tolist()
|
74 |
+
|
75 |
+
def __len__(self):
|
76 |
+
return self.num_samples
|
77 |
+
|
78 |
+
def set_epoch(self, epoch):
|
79 |
+
self.epoch = epoch
|
80 |
+
|
81 |
+
|
82 |
+
class DistributedSequentialSampler(data.sampler.Sampler):
|
83 |
+
def __init__(self, num_samples, train_iters, batch_size, rank=-1, world_size=2):
|
84 |
+
super().__init__(num_samples)
|
85 |
+
if rank == -1:
|
86 |
+
rank = 0
|
87 |
+
world_size = 1
|
88 |
+
self.num_samples = num_samples
|
89 |
+
self.rank = rank
|
90 |
+
self.world_size = world_size
|
91 |
+
self.start_iter = 0
|
92 |
+
self.train_iters = train_iters
|
93 |
+
self.batch_size = batch_size
|
94 |
+
self.batch_bias = [i * (num_samples // batch_size) for i in range(batch_size)]
|
95 |
+
|
96 |
+
def __iter__(self):
|
97 |
+
for idx in range(self.start_iter, self.train_iters * 10):
|
98 |
+
batch = [(idx + bias) % self.num_samples for bias in self.batch_bias]
|
99 |
+
tbatch = self._batch(batch)
|
100 |
+
yield tbatch
|
101 |
+
|
102 |
+
def __len__(self):
|
103 |
+
return self.train_iters
|
104 |
+
|
105 |
+
def _batch(self, batch):
|
106 |
+
"""extracts samples only pertaining to this worker's batch"""
|
107 |
+
start = self.rank*self.batch_size//self.world_size
|
108 |
+
end = (self.rank+1)*self.batch_size//self.world_size
|
109 |
+
return batch[start:end]
|
110 |
+
|
111 |
+
|
112 |
+
class DistributedBatchSampler(data.sampler.BatchSampler):
|
113 |
+
"""
|
114 |
+
similar to normal implementation of distributed sampler, except implementation is at the
|
115 |
+
batch sampler level, instead of just the sampler level. This allows wrapping of arbitrary
|
116 |
+
data samplers (sequential, random, WeightedRandomSampler, etc.) with this batch sampler.
|
117 |
+
"""
|
118 |
+
def __init__(self, sampler, batch_size, drop_last, rank=-1, world_size=2, wrap_last=False, gradient_accumulation_steps=None):
|
119 |
+
super(DistributedBatchSampler, self).__init__(sampler, batch_size, drop_last)
|
120 |
+
if rank == -1:
|
121 |
+
assert False, 'should not be here'
|
122 |
+
self.rank = rank
|
123 |
+
self.world_size = world_size
|
124 |
+
self.sampler.wrap_around = 0
|
125 |
+
self.wrap_around = 0
|
126 |
+
self.wrap_last = wrap_last
|
127 |
+
self.start_iter = 0
|
128 |
+
self.effective_batch_size = batch_size if gradient_accumulation_steps is None else batch_size * gradient_accumulation_steps
|
129 |
+
|
130 |
+
def __iter__(self):
|
131 |
+
batch = []
|
132 |
+
i = 0
|
133 |
+
for idx in self.data_iterator(self.sampler, wrap_around=False):
|
134 |
+
batch.append(idx)
|
135 |
+
if len(batch) == self.batch_size:
|
136 |
+
tbatch = self._batch(batch)
|
137 |
+
if i >= self.start_iter * self.effective_batch_size:
|
138 |
+
yield tbatch
|
139 |
+
self.start_iter = 0
|
140 |
+
i += len(batch)
|
141 |
+
batch = []
|
142 |
+
batch_len = len(batch)
|
143 |
+
if batch_len > 0 and not self.drop_last:
|
144 |
+
if self.wrap_last:
|
145 |
+
self.sampler.wrap_around -= (self.batch_size)
|
146 |
+
self.wrap_around += (len(batch))
|
147 |
+
self.wrap_around %= self.batch_size
|
148 |
+
yield self._batch(batch)
|
149 |
+
if self.wrap_last:
|
150 |
+
self.sampler.wrap_around += self.batch_size
|
151 |
+
|
152 |
+
def data_iterator(self, _iter, wrap_around=False):
|
153 |
+
"""iterates through data and handles wrap around"""
|
154 |
+
for i, idx in enumerate(_iter):
|
155 |
+
if i < self.wrap_around%self.batch_size:
|
156 |
+
continue
|
157 |
+
if wrap_around:
|
158 |
+
self.wrap_around += 1
|
159 |
+
self.wrap_around %= self.batch_size
|
160 |
+
yield idx
|
161 |
+
|
162 |
+
def _batch(self, batch):
|
163 |
+
"""extracts samples only pertaining to this worker's batch"""
|
164 |
+
start = self.rank*self.batch_size//self.world_size
|
165 |
+
end = (self.rank+1)*self.batch_size//self.world_size
|
166 |
+
return batch[start:end]
|
datasets/sft_dataset.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
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 |
+
import copy
|
16 |
+
import os
|
17 |
+
import json
|
18 |
+
from tqdm import tqdm
|
19 |
+
import ipdb
|
20 |
+
import random
|
21 |
+
from torch.nn.utils.rnn import pad_sequence
|
22 |
+
from dataclasses import dataclass, field
|
23 |
+
from typing import Callable, Dict, Sequence
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.distributed as dist
|
27 |
+
import transformers
|
28 |
+
from torch.utils.data import Dataset
|
29 |
+
from tqdm import tqdm
|
30 |
+
|
31 |
+
class SupervisedDataset(Dataset):
|
32 |
+
"""Dataset for supervised fine-tuning."""
|
33 |
+
|
34 |
+
def __init__(self, data_path: str, image_root_path: str):
|
35 |
+
super(SupervisedDataset, self).__init__()
|
36 |
+
|
37 |
+
with open(data_path, 'r') as f:
|
38 |
+
json_data = json.load(f)
|
39 |
+
# for debug:
|
40 |
+
#json_data = json_data[:100000]
|
41 |
+
|
42 |
+
self.image_path_list, self.caption_list = [], []
|
43 |
+
for item in json_data:
|
44 |
+
one_image_name, one_caption = item["image_name"], item["conversation"]
|
45 |
+
# TODO: stage 2 dataset format is invalid
|
46 |
+
if not one_image_name.endswith('.jpg'):
|
47 |
+
one_image_name += '.jpg'
|
48 |
+
one_image_path = image_root_path + '/{}'.format(one_image_name)
|
49 |
+
self.image_path_list.append(one_image_path)
|
50 |
+
self.caption_list.append(one_caption)
|
51 |
+
print(f'[!] collect {len(self.image_path_list)} samples for training')
|
52 |
+
|
53 |
+
def __len__(self): # number of instances
|
54 |
+
return len(self.image_path_list)
|
55 |
+
|
56 |
+
#def __getitem__(self, i) -> Dict[str, torch.Tensor]: # how to get item, 取一个样本
|
57 |
+
def __getitem__(self, i):
|
58 |
+
return dict(image_paths=self.image_path_list[i], output_texts=self.caption_list[i])
|
59 |
+
|
60 |
+
def collate(self, instances):
|
61 |
+
image_paths, output_texts = tuple([instance[key] for instance in instances] for key in ("image_paths", "output_texts"))
|
62 |
+
return dict(
|
63 |
+
image_paths=image_paths,
|
64 |
+
output_texts=output_texts
|
65 |
+
)
|
dsconfig/openllama_peft_stage_1.json
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"train_batch_size": 64,
|
3 |
+
"train_micro_batch_size_per_gpu": 1,
|
4 |
+
"gradient_accumulation_steps": 8,
|
5 |
+
"steps_per_print": 1,
|
6 |
+
"gradient_clipping": 1.0,
|
7 |
+
"zero_optimization": {
|
8 |
+
"stage": 2,
|
9 |
+
"offload_optimizer": {
|
10 |
+
"device": "cpu"
|
11 |
+
},
|
12 |
+
"contiguous_gradients": true,
|
13 |
+
"allgather_bucket_size": 500000000,
|
14 |
+
"allgather_partitions": true
|
15 |
+
},
|
16 |
+
"fp16": {
|
17 |
+
"enabled": true,
|
18 |
+
"opt_level": "O2",
|
19 |
+
"min_loss_scale": 1
|
20 |
+
},
|
21 |
+
"bf16": {
|
22 |
+
"enable": true
|
23 |
+
},
|
24 |
+
"optimizer": {
|
25 |
+
"type": "Adam",
|
26 |
+
"params": {
|
27 |
+
"lr": 0.0005,
|
28 |
+
"betas": [
|
29 |
+
0.9,
|
30 |
+
0.95
|
31 |
+
],
|
32 |
+
"eps": 1e-8,
|
33 |
+
"weight_decay": 0.001
|
34 |
+
}
|
35 |
+
},
|
36 |
+
"scheduler": {
|
37 |
+
"type": "WarmupDecayLR",
|
38 |
+
"params": {
|
39 |
+
"warmup_min_lr": 0,
|
40 |
+
"warmup_max_lr": 0.0005,
|
41 |
+
"warmup_num_steps": 10,
|
42 |
+
"total_num_steps": 10000
|
43 |
+
}
|
44 |
+
},
|
45 |
+
"activation_checkpointing": {
|
46 |
+
"partition_activations": true,
|
47 |
+
"cpu_checkpointing": true,
|
48 |
+
"contiguous_memory_optimization": false,
|
49 |
+
"number_checkpoints": null,
|
50 |
+
"synchronize_checkpoint_boundary": false,
|
51 |
+
"profile": false
|
52 |
+
}
|
53 |
+
|
54 |
+
}
|
header.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import datetime
|
3 |
+
import types
|
4 |
+
import deepspeed
|
5 |
+
from transformers.deepspeed import HfDeepSpeedConfig
|
6 |
+
import transformers
|
7 |
+
import numpy as np
|
8 |
+
from collections import OrderedDict
|
9 |
+
from torch.utils.data import Dataset, DataLoader
|
10 |
+
from torch.nn.utils import clip_grad_norm_
|
11 |
+
from torch.cuda.amp import autocast, GradScaler
|
12 |
+
from torch.nn import DataParallel
|
13 |
+
from torch.optim import lr_scheduler
|
14 |
+
import torch.optim as optim
|
15 |
+
import torch.nn as nn
|
16 |
+
import torch.nn.functional as F
|
17 |
+
from tqdm import tqdm
|
18 |
+
import os
|
19 |
+
import re
|
20 |
+
import math
|
21 |
+
import random
|
22 |
+
import json
|
23 |
+
import time
|
24 |
+
import logging
|
25 |
+
from copy import deepcopy
|
26 |
+
import ipdb
|
27 |
+
import argparse
|
28 |
+
import data
|
29 |
+
from transformers import LlamaTokenizer, LlamaForCausalLM, LlamaConfig
|
30 |
+
from torch.nn.utils.rnn import pad_sequence
|
31 |
+
from peft import LoraConfig, TaskType, get_peft_model
|
32 |
+
|
33 |
+
logging.getLogger("transformers").setLevel(logging.WARNING)
|
34 |
+
logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR)
|
35 |
+
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
|
model/ImageBind/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Code of Conduct
|
2 |
+
|
3 |
+
## Our Pledge
|
4 |
+
|
5 |
+
In the interest of fostering an open and welcoming environment, we as
|
6 |
+
contributors and maintainers pledge to make participation in our project and
|
7 |
+
our community a harassment-free experience for everyone, regardless of age, body
|
8 |
+
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
9 |
+
level of experience, education, socio-economic status, nationality, personal
|
10 |
+
appearance, race, religion, or sexual identity and orientation.
|
11 |
+
|
12 |
+
## Our Standards
|
13 |
+
|
14 |
+
Examples of behavior that contributes to creating a positive environment
|
15 |
+
include:
|
16 |
+
|
17 |
+
* Using welcoming and inclusive language
|
18 |
+
* Being respectful of differing viewpoints and experiences
|
19 |
+
* Gracefully accepting constructive criticism
|
20 |
+
* Focusing on what is best for the community
|
21 |
+
* Showing empathy towards other community members
|
22 |
+
|
23 |
+
Examples of unacceptable behavior by participants include:
|
24 |
+
|
25 |
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
26 |
+
advances
|
27 |
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
28 |
+
* Public or private harassment
|
29 |
+
* Publishing others' private information, such as a physical or electronic
|
30 |
+
address, without explicit permission
|
31 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
32 |
+
professional setting
|
33 |
+
|
34 |
+
## Our Responsibilities
|
35 |
+
|
36 |
+
Project maintainers are responsible for clarifying the standards of acceptable
|
37 |
+
behavior and are expected to take appropriate and fair corrective action in
|
38 |
+
response to any instances of unacceptable behavior.
|
39 |
+
|
40 |
+
Project maintainers have the right and responsibility to remove, edit, or
|
41 |
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
42 |
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
43 |
+
permanently any contributor for other behaviors that they deem inappropriate,
|
44 |
+
threatening, offensive, or harmful.
|
45 |
+
|
46 |
+
## Scope
|
47 |
+
|
48 |
+
This Code of Conduct applies within all project spaces, and it also applies when
|
49 |
+
an individual is representing the project or its community in public spaces.
|
50 |
+
Examples of representing a project or community include using an official
|
51 |
+
project e-mail address, posting via an official social media account, or acting
|
52 |
+
as an appointed representative at an online or offline event. Representation of
|
53 |
+
a project may be further defined and clarified by project maintainers.
|
54 |
+
|
55 |
+
This Code of Conduct also applies outside the project spaces when there is a
|
56 |
+
reasonable belief that an individual's behavior may have a negative impact on
|
57 |
+
the project or its community.
|
58 |
+
|
59 |
+
## Enforcement
|
60 |
+
|
61 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62 |
+
reported by contacting the project team at <opensource-conduct@fb.com>. All
|
63 |
+
complaints will be reviewed and investigated and will result in a response that
|
64 |
+
is deemed necessary and appropriate to the circumstances. The project team is
|
65 |
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
66 |
+
Further details of specific enforcement policies may be posted separately.
|
67 |
+
|
68 |
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
69 |
+
faith may face temporary or permanent repercussions as determined by other
|
70 |
+
members of the project's leadership.
|
71 |
+
|
72 |
+
## Attribution
|
73 |
+
|
74 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
75 |
+
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
76 |
+
|
77 |
+
[homepage]: https://www.contributor-covenant.org
|
78 |
+
|
79 |
+
For answers to common questions about this code of conduct, see
|
80 |
+
https://www.contributor-covenant.org/faq
|
model/ImageBind/CONTRIBUTING.md
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributing to ImageBind
|
2 |
+
We want to make contributing to this project as easy and transparent as
|
3 |
+
possible.
|
4 |
+
|
5 |
+
## Pull Requests
|
6 |
+
We actively welcome your pull requests.
|
7 |
+
|
8 |
+
1. Fork the repo and create your branch from `main`.
|
9 |
+
2. If you've added code that should be tested, add tests.
|
10 |
+
3. If you've changed APIs, update the documentation.
|
11 |
+
4. Ensure the test suite passes.
|
12 |
+
5. Make sure your code lints.
|
13 |
+
6. If you haven't already, complete the Contributor License Agreement ("CLA").
|
14 |
+
|
15 |
+
## Contributor License Agreement ("CLA")
|
16 |
+
In order to accept your pull request, we need you to submit a CLA. You only need
|
17 |
+
to do this once to work on any of Meta's open source projects.
|
18 |
+
|
19 |
+
Complete your CLA here: <https://code.facebook.com/cla>
|
20 |
+
|
21 |
+
## Issues
|
22 |
+
We use GitHub issues to track public bugs. Please ensure your description is
|
23 |
+
clear and has sufficient instructions to be able to reproduce the issue.
|
24 |
+
|
25 |
+
Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
|
26 |
+
disclosure of security bugs. In those cases, please go through the process
|
27 |
+
outlined on that page and do not file a public issue.
|
28 |
+
|
29 |
+
## License
|
30 |
+
By contributing to Omnivore, you agree that your contributions will be licensed
|
31 |
+
under the [LICENSE](LICENSE) file in the root directory of this source tree.
|
model/ImageBind/LICENSE
ADDED
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Attribution-NonCommercial-ShareAlike 4.0 International
|
2 |
+
|
3 |
+
=======================================================================
|
4 |
+
|
5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
6 |
+
does not provide legal services or legal advice. Distribution of
|
7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
8 |
+
other relationship. Creative Commons makes its licenses and related
|
9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
10 |
+
warranties regarding its licenses, any material licensed under their
|
11 |
+
terms and conditions, or any related information. Creative Commons
|
12 |
+
disclaims all liability for damages resulting from their use to the
|
13 |
+
fullest extent possible.
|
14 |
+
|
15 |
+
Using Creative Commons Public Licenses
|
16 |
+
|
17 |
+
Creative Commons public licenses provide a standard set of terms and
|
18 |
+
conditions that creators and other rights holders may use to share
|
19 |
+
original works of authorship and other material subject to copyright
|
20 |
+
and certain other rights specified in the public license below. The
|
21 |
+
following considerations are for informational purposes only, are not
|
22 |
+
exhaustive, and do not form part of our licenses.
|
23 |
+
|
24 |
+
Considerations for licensors: Our public licenses are
|
25 |
+
intended for use by those authorized to give the public
|
26 |
+
permission to use material in ways otherwise restricted by
|
27 |
+
copyright and certain other rights. Our licenses are
|
28 |
+
irrevocable. Licensors should read and understand the terms
|
29 |
+
and conditions of the license they choose before applying it.
|
30 |
+
Licensors should also secure all rights necessary before
|
31 |
+
applying our licenses so that the public can reuse the
|
32 |
+
material as expected. Licensors should clearly mark any
|
33 |
+
material not subject to the license. This includes other CC-
|
34 |
+
licensed material, or material used under an exception or
|
35 |
+
limitation to copyright. More considerations for licensors:
|
36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
37 |
+
|
38 |
+
Considerations for the public: By using one of our public
|
39 |
+
licenses, a licensor grants the public permission to use the
|
40 |
+
licensed material under specified terms and conditions. If
|
41 |
+
the licensor's permission is not necessary for any reason--for
|
42 |
+
example, because of any applicable exception or limitation to
|
43 |
+
copyright--then that use is not regulated by the license. Our
|
44 |
+
licenses grant only permissions under copyright and certain
|
45 |
+
other rights that a licensor has authority to grant. Use of
|
46 |
+
the licensed material may still be restricted for other
|
47 |
+
reasons, including because others have copyright or other
|
48 |
+
rights in the material. A licensor may make special requests,
|
49 |
+
such as asking that all changes be marked or described.
|
50 |
+
Although not required by our licenses, you are encouraged to
|
51 |
+
respect those requests where reasonable. More considerations
|
52 |
+
for the public:
|
53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
54 |
+
|
55 |
+
=======================================================================
|
56 |
+
|
57 |
+
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
58 |
+
Public License
|
59 |
+
|
60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
61 |
+
to be bound by the terms and conditions of this Creative Commons
|
62 |
+
Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
63 |
+
("Public License"). To the extent this Public License may be
|
64 |
+
interpreted as a contract, You are granted the Licensed Rights in
|
65 |
+
consideration of Your acceptance of these terms and conditions, and the
|
66 |
+
Licensor grants You such rights in consideration of benefits the
|
67 |
+
Licensor receives from making the Licensed Material available under
|
68 |
+
these terms and conditions.
|
69 |
+
|
70 |
+
|
71 |
+
Section 1 -- Definitions.
|
72 |
+
|
73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
74 |
+
Rights that is derived from or based upon the Licensed Material
|
75 |
+
and in which the Licensed Material is translated, altered,
|
76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
77 |
+
permission under the Copyright and Similar Rights held by the
|
78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
79 |
+
Material is a musical work, performance, or sound recording,
|
80 |
+
Adapted Material is always produced where the Licensed Material is
|
81 |
+
synched in timed relation with a moving image.
|
82 |
+
|
83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
85 |
+
accordance with the terms and conditions of this Public License.
|
86 |
+
|
87 |
+
c. BY-NC-SA Compatible License means a license listed at
|
88 |
+
creativecommons.org/compatiblelicenses, approved by Creative
|
89 |
+
Commons as essentially the equivalent of this Public License.
|
90 |
+
|
91 |
+
d. Copyright and Similar Rights means copyright and/or similar rights
|
92 |
+
closely related to copyright including, without limitation,
|
93 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
94 |
+
Rights, without regard to how the rights are labeled or
|
95 |
+
categorized. For purposes of this Public License, the rights
|
96 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
97 |
+
Rights.
|
98 |
+
|
99 |
+
e. Effective Technological Measures means those measures that, in the
|
100 |
+
absence of proper authority, may not be circumvented under laws
|
101 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
102 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
103 |
+
agreements.
|
104 |
+
|
105 |
+
f. Exceptions and Limitations means fair use, fair dealing, and/or
|
106 |
+
any other exception or limitation to Copyright and Similar Rights
|
107 |
+
that applies to Your use of the Licensed Material.
|
108 |
+
|
109 |
+
g. License Elements means the license attributes listed in the name
|
110 |
+
of a Creative Commons Public License. The License Elements of this
|
111 |
+
Public License are Attribution, NonCommercial, and ShareAlike.
|
112 |
+
|
113 |
+
h. Licensed Material means the artistic or literary work, database,
|
114 |
+
or other material to which the Licensor applied this Public
|
115 |
+
License.
|
116 |
+
|
117 |
+
i. Licensed Rights means the rights granted to You subject to the
|
118 |
+
terms and conditions of this Public License, which are limited to
|
119 |
+
all Copyright and Similar Rights that apply to Your use of the
|
120 |
+
Licensed Material and that the Licensor has authority to license.
|
121 |
+
|
122 |
+
j. Licensor means the individual(s) or entity(ies) granting rights
|
123 |
+
under this Public License.
|
124 |
+
|
125 |
+
k. NonCommercial means not primarily intended for or directed towards
|
126 |
+
commercial advantage or monetary compensation. For purposes of
|
127 |
+
this Public License, the exchange of the Licensed Material for
|
128 |
+
other material subject to Copyright and Similar Rights by digital
|
129 |
+
file-sharing or similar means is NonCommercial provided there is
|
130 |
+
no payment of monetary compensation in connection with the
|
131 |
+
exchange.
|
132 |
+
|
133 |
+
l. Share means to provide material to the public by any means or
|
134 |
+
process that requires permission under the Licensed Rights, such
|
135 |
+
as reproduction, public display, public performance, distribution,
|
136 |
+
dissemination, communication, or importation, and to make material
|
137 |
+
available to the public including in ways that members of the
|
138 |
+
public may access the material from a place and at a time
|
139 |
+
individually chosen by them.
|
140 |
+
|
141 |
+
m. Sui Generis Database Rights means rights other than copyright
|
142 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
143 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
144 |
+
as amended and/or succeeded, as well as other essentially
|
145 |
+
equivalent rights anywhere in the world.
|
146 |
+
|
147 |
+
n. You means the individual or entity exercising the Licensed Rights
|
148 |
+
under this Public License. Your has a corresponding meaning.
|
149 |
+
|
150 |
+
|
151 |
+
Section 2 -- Scope.
|
152 |
+
|
153 |
+
a. License grant.
|
154 |
+
|
155 |
+
1. Subject to the terms and conditions of this Public License,
|
156 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
157 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
158 |
+
exercise the Licensed Rights in the Licensed Material to:
|
159 |
+
|
160 |
+
a. reproduce and Share the Licensed Material, in whole or
|
161 |
+
in part, for NonCommercial purposes only; and
|
162 |
+
|
163 |
+
b. produce, reproduce, and Share Adapted Material for
|
164 |
+
NonCommercial purposes only.
|
165 |
+
|
166 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
167 |
+
Exceptions and Limitations apply to Your use, this Public
|
168 |
+
License does not apply, and You do not need to comply with
|
169 |
+
its terms and conditions.
|
170 |
+
|
171 |
+
3. Term. The term of this Public License is specified in Section
|
172 |
+
6(a).
|
173 |
+
|
174 |
+
4. Media and formats; technical modifications allowed. The
|
175 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
176 |
+
all media and formats whether now known or hereafter created,
|
177 |
+
and to make technical modifications necessary to do so. The
|
178 |
+
Licensor waives and/or agrees not to assert any right or
|
179 |
+
authority to forbid You from making technical modifications
|
180 |
+
necessary to exercise the Licensed Rights, including
|
181 |
+
technical modifications necessary to circumvent Effective
|
182 |
+
Technological Measures. For purposes of this Public License,
|
183 |
+
simply making modifications authorized by this Section 2(a)
|
184 |
+
(4) never produces Adapted Material.
|
185 |
+
|
186 |
+
5. Downstream recipients.
|
187 |
+
|
188 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
189 |
+
recipient of the Licensed Material automatically
|
190 |
+
receives an offer from the Licensor to exercise the
|
191 |
+
Licensed Rights under the terms and conditions of this
|
192 |
+
Public License.
|
193 |
+
|
194 |
+
b. Additional offer from the Licensor -- Adapted Material.
|
195 |
+
Every recipient of Adapted Material from You
|
196 |
+
automatically receives an offer from the Licensor to
|
197 |
+
exercise the Licensed Rights in the Adapted Material
|
198 |
+
under the conditions of the Adapter's License You apply.
|
199 |
+
|
200 |
+
c. No downstream restrictions. You may not offer or impose
|
201 |
+
any additional or different terms or conditions on, or
|
202 |
+
apply any Effective Technological Measures to, the
|
203 |
+
Licensed Material if doing so restricts exercise of the
|
204 |
+
Licensed Rights by any recipient of the Licensed
|
205 |
+
Material.
|
206 |
+
|
207 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
208 |
+
may be construed as permission to assert or imply that You
|
209 |
+
are, or that Your use of the Licensed Material is, connected
|
210 |
+
with, or sponsored, endorsed, or granted official status by,
|
211 |
+
the Licensor or others designated to receive attribution as
|
212 |
+
provided in Section 3(a)(1)(A)(i).
|
213 |
+
|
214 |
+
b. Other rights.
|
215 |
+
|
216 |
+
1. Moral rights, such as the right of integrity, are not
|
217 |
+
licensed under this Public License, nor are publicity,
|
218 |
+
privacy, and/or other similar personality rights; however, to
|
219 |
+
the extent possible, the Licensor waives and/or agrees not to
|
220 |
+
assert any such rights held by the Licensor to the limited
|
221 |
+
extent necessary to allow You to exercise the Licensed
|
222 |
+
Rights, but not otherwise.
|
223 |
+
|
224 |
+
2. Patent and trademark rights are not licensed under this
|
225 |
+
Public License.
|
226 |
+
|
227 |
+
3. To the extent possible, the Licensor waives any right to
|
228 |
+
collect royalties from You for the exercise of the Licensed
|
229 |
+
Rights, whether directly or through a collecting society
|
230 |
+
under any voluntary or waivable statutory or compulsory
|
231 |
+
licensing scheme. In all other cases the Licensor expressly
|
232 |
+
reserves any right to collect such royalties, including when
|
233 |
+
the Licensed Material is used other than for NonCommercial
|
234 |
+
purposes.
|
235 |
+
|
236 |
+
|
237 |
+
Section 3 -- License Conditions.
|
238 |
+
|
239 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
240 |
+
following conditions.
|
241 |
+
|
242 |
+
a. Attribution.
|
243 |
+
|
244 |
+
1. If You Share the Licensed Material (including in modified
|
245 |
+
form), You must:
|
246 |
+
|
247 |
+
a. retain the following if it is supplied by the Licensor
|
248 |
+
with the Licensed Material:
|
249 |
+
|
250 |
+
i. identification of the creator(s) of the Licensed
|
251 |
+
Material and any others designated to receive
|
252 |
+
attribution, in any reasonable manner requested by
|
253 |
+
the Licensor (including by pseudonym if
|
254 |
+
designated);
|
255 |
+
|
256 |
+
ii. a copyright notice;
|
257 |
+
|
258 |
+
iii. a notice that refers to this Public License;
|
259 |
+
|
260 |
+
iv. a notice that refers to the disclaimer of
|
261 |
+
warranties;
|
262 |
+
|
263 |
+
v. a URI or hyperlink to the Licensed Material to the
|
264 |
+
extent reasonably practicable;
|
265 |
+
|
266 |
+
b. indicate if You modified the Licensed Material and
|
267 |
+
retain an indication of any previous modifications; and
|
268 |
+
|
269 |
+
c. indicate the Licensed Material is licensed under this
|
270 |
+
Public License, and include the text of, or the URI or
|
271 |
+
hyperlink to, this Public License.
|
272 |
+
|
273 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
274 |
+
reasonable manner based on the medium, means, and context in
|
275 |
+
which You Share the Licensed Material. For example, it may be
|
276 |
+
reasonable to satisfy the conditions by providing a URI or
|
277 |
+
hyperlink to a resource that includes the required
|
278 |
+
information.
|
279 |
+
3. If requested by the Licensor, You must remove any of the
|
280 |
+
information required by Section 3(a)(1)(A) to the extent
|
281 |
+
reasonably practicable.
|
282 |
+
|
283 |
+
b. ShareAlike.
|
284 |
+
|
285 |
+
In addition to the conditions in Section 3(a), if You Share
|
286 |
+
Adapted Material You produce, the following conditions also apply.
|
287 |
+
|
288 |
+
1. The Adapter's License You apply must be a Creative Commons
|
289 |
+
license with the same License Elements, this version or
|
290 |
+
later, or a BY-NC-SA Compatible License.
|
291 |
+
|
292 |
+
2. You must include the text of, or the URI or hyperlink to, the
|
293 |
+
Adapter's License You apply. You may satisfy this condition
|
294 |
+
in any reasonable manner based on the medium, means, and
|
295 |
+
context in which You Share Adapted Material.
|
296 |
+
|
297 |
+
3. You may not offer or impose any additional or different terms
|
298 |
+
or conditions on, or apply any Effective Technological
|
299 |
+
Measures to, Adapted Material that restrict exercise of the
|
300 |
+
rights granted under the Adapter's License You apply.
|
301 |
+
|
302 |
+
|
303 |
+
Section 4 -- Sui Generis Database Rights.
|
304 |
+
|
305 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
306 |
+
apply to Your use of the Licensed Material:
|
307 |
+
|
308 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
309 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
310 |
+
portion of the contents of the database for NonCommercial purposes
|
311 |
+
only;
|
312 |
+
|
313 |
+
b. if You include all or a substantial portion of the database
|
314 |
+
contents in a database in which You have Sui Generis Database
|
315 |
+
Rights, then the database in which You have Sui Generis Database
|
316 |
+
Rights (but not its individual contents) is Adapted Material,
|
317 |
+
including for purposes of Section 3(b); and
|
318 |
+
|
319 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
320 |
+
all or a substantial portion of the contents of the database.
|
321 |
+
|
322 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
323 |
+
replace Your obligations under this Public License where the Licensed
|
324 |
+
Rights include other Copyright and Similar Rights.
|
325 |
+
|
326 |
+
|
327 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
328 |
+
|
329 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
330 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
331 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
332 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
333 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
334 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
335 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
336 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
337 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
338 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
339 |
+
|
340 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
341 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
342 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
343 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
344 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
345 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
346 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
347 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
348 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
349 |
+
|
350 |
+
c. The disclaimer of warranties and limitation of liability provided
|
351 |
+
above shall be interpreted in a manner that, to the extent
|
352 |
+
possible, most closely approximates an absolute disclaimer and
|
353 |
+
waiver of all liability.
|
354 |
+
|
355 |
+
|
356 |
+
Section 6 -- Term and Termination.
|
357 |
+
|
358 |
+
a. This Public License applies for the term of the Copyright and
|
359 |
+
Similar Rights licensed here. However, if You fail to comply with
|
360 |
+
this Public License, then Your rights under this Public License
|
361 |
+
terminate automatically.
|
362 |
+
|
363 |
+
b. Where Your right to use the Licensed Material has terminated under
|
364 |
+
Section 6(a), it reinstates:
|
365 |
+
|
366 |
+
1. automatically as of the date the violation is cured, provided
|
367 |
+
it is cured within 30 days of Your discovery of the
|
368 |
+
violation; or
|
369 |
+
|
370 |
+
2. upon express reinstatement by the Licensor.
|
371 |
+
|
372 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
373 |
+
right the Licensor may have to seek remedies for Your violations
|
374 |
+
of this Public License.
|
375 |
+
|
376 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
377 |
+
Licensed Material under separate terms or conditions or stop
|
378 |
+
distributing the Licensed Material at any time; however, doing so
|
379 |
+
will not terminate this Public License.
|
380 |
+
|
381 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
382 |
+
License.
|
383 |
+
|
384 |
+
|
385 |
+
Section 7 -- Other Terms and Conditions.
|
386 |
+
|
387 |
+
a. The Licensor shall not be bound by any additional or different
|
388 |
+
terms or conditions communicated by You unless expressly agreed.
|
389 |
+
|
390 |
+
b. Any arrangements, understandings, or agreements regarding the
|
391 |
+
Licensed Material not stated herein are separate from and
|
392 |
+
independent of the terms and conditions of this Public License.
|
393 |
+
|
394 |
+
|
395 |
+
Section 8 -- Interpretation.
|
396 |
+
|
397 |
+
a. For the avoidance of doubt, this Public License does not, and
|
398 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
399 |
+
conditions on any use of the Licensed Material that could lawfully
|
400 |
+
be made without permission under this Public License.
|
401 |
+
|
402 |
+
b. To the extent possible, if any provision of this Public License is
|
403 |
+
deemed unenforceable, it shall be automatically reformed to the
|
404 |
+
minimum extent necessary to make it enforceable. If the provision
|
405 |
+
cannot be reformed, it shall be severed from this Public License
|
406 |
+
without affecting the enforceability of the remaining terms and
|
407 |
+
conditions.
|
408 |
+
|
409 |
+
c. No term or condition of this Public License will be waived and no
|
410 |
+
failure to comply consented to unless expressly agreed to by the
|
411 |
+
Licensor.
|
412 |
+
|
413 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
414 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
415 |
+
that apply to the Licensor or You, including from the legal
|
416 |
+
processes of any jurisdiction or authority.
|
417 |
+
|
418 |
+
=======================================================================
|
419 |
+
|
420 |
+
Creative Commons is not a party to its public
|
421 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
422 |
+
its public licenses to material it publishes and in those instances
|
423 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
424 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
425 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
426 |
+
material is shared under a Creative Commons public license or as
|
427 |
+
otherwise permitted by the Creative Commons policies published at
|
428 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
429 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
430 |
+
of Creative Commons without its prior written consent including,
|
431 |
+
without limitation, in connection with any unauthorized modifications
|
432 |
+
to any of its public licenses or any other arrangements,
|
433 |
+
understandings, or agreements concerning use of licensed material. For
|
434 |
+
the avoidance of doubt, this paragraph does not form part of the
|
435 |
+
public licenses.
|
436 |
+
|
437 |
+
Creative Commons may be contacted at creativecommons.org.
|
model/ImageBind/README.md
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ImageBind: One Embedding Space To Bind Them All
|
2 |
+
|
3 |
+
**[FAIR, Meta AI](https://ai.facebook.com/research/)**
|
4 |
+
|
5 |
+
Rohit Girdhar*,
|
6 |
+
Alaaeldin El-Nouby*,
|
7 |
+
Zhuang Liu,
|
8 |
+
Mannat Singh,
|
9 |
+
Kalyan Vasudev Alwala,
|
10 |
+
Armand Joulin,
|
11 |
+
Ishan Misra*
|
12 |
+
|
13 |
+
To appear at CVPR 2023 (*Highlighted paper*)
|
14 |
+
|
15 |
+
[[`Paper`](https://facebookresearch.github.io/ImageBind/paper)] [[`Blog`](https://ai.facebook.com/blog/imagebind-six-modalities-binding-ai/)] [[`Demo`](https://imagebind.metademolab.com/)] [[`Supplementary Video`](https://dl.fbaipublicfiles.com/imagebind/imagebind_video.mp4)] [[`BibTex`](#citing-imagebind)]
|
16 |
+
|
17 |
+
PyTorch implementation and pretrained models for ImageBind. For details, see the paper: **[ImageBind: One Embedding Space To Bind Them All](https://facebookresearch.github.io/ImageBind/paper)**.
|
18 |
+
|
19 |
+
ImageBind learns a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data. It enables novel emergent applications ‘out-of-the-box’ including cross-modal retrieval, composing modalities with arithmetic, cross-modal detection and generation.
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
![ImageBind](https://user-images.githubusercontent.com/8495451/236859695-ffa13364-3e39-4d99-a8da-fbfab17f9a6b.gif)
|
24 |
+
|
25 |
+
## ImageBind model
|
26 |
+
|
27 |
+
Emergent zero-shot classification performance.
|
28 |
+
|
29 |
+
<table style="margin: auto">
|
30 |
+
<tr>
|
31 |
+
<th>Model</th>
|
32 |
+
<th><span style="color:blue">IN1k</span></th>
|
33 |
+
<th><span style="color:purple">K400</span></th>
|
34 |
+
<th><span style="color:green">NYU-D</span></th>
|
35 |
+
<th><span style="color:LightBlue">ESC</span></th>
|
36 |
+
<th><span style="color:orange">LLVIP</span></th>
|
37 |
+
<th><span style="color:purple">Ego4D</span></th>
|
38 |
+
<th>download</th>
|
39 |
+
</tr>
|
40 |
+
<tr>
|
41 |
+
<td>imagebind_huge</td>
|
42 |
+
<td align="right">77.7</td>
|
43 |
+
<td align="right">50.0</td>
|
44 |
+
<td align="right">54.0</td>
|
45 |
+
<td align="right">66.9</td>
|
46 |
+
<td align="right">63.4</td>
|
47 |
+
<td align="right">25.0</td>
|
48 |
+
<td><a href="https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth">checkpoint</a></td>
|
49 |
+
</tr>
|
50 |
+
|
51 |
+
</table>
|
52 |
+
|
53 |
+
## Usage
|
54 |
+
|
55 |
+
Install pytorch 1.13+ and other 3rd party dependencies.
|
56 |
+
|
57 |
+
```shell
|
58 |
+
conda create --name imagebind python=3.8 -y
|
59 |
+
conda activate imagebind
|
60 |
+
|
61 |
+
pip install -r requirements.txt
|
62 |
+
```
|
63 |
+
|
64 |
+
For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977)
|
65 |
+
|
66 |
+
```
|
67 |
+
pip install soundfile
|
68 |
+
```
|
69 |
+
|
70 |
+
|
71 |
+
Extract and compare features across modalities (e.g. Image, Text and Audio).
|
72 |
+
|
73 |
+
```python
|
74 |
+
import data
|
75 |
+
import torch
|
76 |
+
from models import imagebind_model
|
77 |
+
from models.imagebind_model import ModalityType
|
78 |
+
|
79 |
+
text_list=["A dog.", "A car", "A bird"]
|
80 |
+
image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"]
|
81 |
+
audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"]
|
82 |
+
|
83 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
84 |
+
|
85 |
+
# Instantiate model
|
86 |
+
model = imagebind_model.imagebind_huge(pretrained=True)
|
87 |
+
model.eval()
|
88 |
+
model.to(device)
|
89 |
+
|
90 |
+
# Load data
|
91 |
+
inputs = {
|
92 |
+
ModalityType.TEXT: data.load_and_transform_text(text_list, device),
|
93 |
+
ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),
|
94 |
+
ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device),
|
95 |
+
}
|
96 |
+
|
97 |
+
with torch.no_grad():
|
98 |
+
embeddings = model(inputs)
|
99 |
+
|
100 |
+
print(
|
101 |
+
"Vision x Text: ",
|
102 |
+
torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1),
|
103 |
+
)
|
104 |
+
print(
|
105 |
+
"Audio x Text: ",
|
106 |
+
torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1),
|
107 |
+
)
|
108 |
+
print(
|
109 |
+
"Vision x Audio: ",
|
110 |
+
torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1),
|
111 |
+
)
|
112 |
+
|
113 |
+
# Expected output:
|
114 |
+
#
|
115 |
+
# Vision x Text:
|
116 |
+
# tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05],
|
117 |
+
# [3.3836e-05, 9.9994e-01, 2.4118e-05],
|
118 |
+
# [4.7997e-05, 1.3496e-02, 9.8646e-01]])
|
119 |
+
#
|
120 |
+
# Audio x Text:
|
121 |
+
# tensor([[1., 0., 0.],
|
122 |
+
# [0., 1., 0.],
|
123 |
+
# [0., 0., 1.]])
|
124 |
+
#
|
125 |
+
# Vision x Audio:
|
126 |
+
# tensor([[0.8070, 0.1088, 0.0842],
|
127 |
+
# [0.1036, 0.7884, 0.1079],
|
128 |
+
# [0.0018, 0.0022, 0.9960]])
|
129 |
+
|
130 |
+
```
|
131 |
+
|
132 |
+
## Model card
|
133 |
+
Please see the [model card](model_card.md) for details.
|
134 |
+
|
135 |
+
## License
|
136 |
+
|
137 |
+
ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
|
138 |
+
|
139 |
+
## Contributing
|
140 |
+
|
141 |
+
See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
|
142 |
+
|
143 |
+
## Citing ImageBind
|
144 |
+
|
145 |
+
If you find this repository useful, please consider giving a star :star: and citation
|
146 |
+
|
147 |
+
```
|
148 |
+
@inproceedings{girdhar2023imagebind,
|
149 |
+
title={ImageBind: One Embedding Space To Bind Them All},
|
150 |
+
author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
|
151 |
+
and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
|
152 |
+
booktitle={CVPR},
|
153 |
+
year={2023}
|
154 |
+
}
|
155 |
+
```
|
model/ImageBind/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from .models import imagebind_model
|
2 |
+
from .models.imagebind_model import ModalityType
|
model/ImageBind/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (258 Bytes). View file
|
|
model/ImageBind/__pycache__/data.cpython-39.pyc
ADDED
Binary file (9.79 kB). View file
|
|
model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
|
3 |
+
size 1356917
|
model/ImageBind/data.py
ADDED
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
|
3 |
+
# All rights reserved.
|
4 |
+
|
5 |
+
# This source code is licensed under the license found in the
|
6 |
+
# LICENSE file in the root directory of this source tree.
|
7 |
+
|
8 |
+
import math
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
import torchaudio
|
13 |
+
import logging
|
14 |
+
|
15 |
+
from .models.multimodal_preprocessors import SimpleTokenizer
|
16 |
+
from PIL import Image
|
17 |
+
from pytorchvideo import transforms as pv_transforms
|
18 |
+
from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
|
19 |
+
from pytorchvideo.data.encoded_video import EncodedVideo
|
20 |
+
|
21 |
+
from torchvision import transforms
|
22 |
+
from torchvision.transforms._transforms_video import NormalizeVideo
|
23 |
+
|
24 |
+
DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
|
25 |
+
|
26 |
+
BPE_PATH = "bpe/bpe_simple_vocab_16e6.txt.gz"
|
27 |
+
|
28 |
+
|
29 |
+
def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
|
30 |
+
# Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
|
31 |
+
waveform -= waveform.mean()
|
32 |
+
fbank = torchaudio.compliance.kaldi.fbank(
|
33 |
+
waveform,
|
34 |
+
htk_compat=True,
|
35 |
+
sample_frequency=sample_rate,
|
36 |
+
use_energy=False,
|
37 |
+
window_type="hanning",
|
38 |
+
num_mel_bins=num_mel_bins,
|
39 |
+
dither=0.0,
|
40 |
+
frame_length=25,
|
41 |
+
frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
|
42 |
+
)
|
43 |
+
# Convert to [mel_bins, num_frames] shape
|
44 |
+
fbank = fbank.transpose(0, 1)
|
45 |
+
# Pad to target_length
|
46 |
+
n_frames = fbank.size(1)
|
47 |
+
p = target_length - n_frames
|
48 |
+
# if p is too large (say >20%), flash a warning
|
49 |
+
if abs(p) / n_frames > 0.2:
|
50 |
+
logging.warning(
|
51 |
+
"Large gap between audio n_frames(%d) and "
|
52 |
+
"target_length (%d). Is the audio_target_length "
|
53 |
+
"setting correct?",
|
54 |
+
n_frames,
|
55 |
+
target_length,
|
56 |
+
)
|
57 |
+
# cut and pad
|
58 |
+
if p > 0:
|
59 |
+
fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
|
60 |
+
elif p < 0:
|
61 |
+
fbank = fbank[:, 0:target_length]
|
62 |
+
# Convert to [1, mel_bins, num_frames] shape, essentially like a 1
|
63 |
+
# channel image
|
64 |
+
fbank = fbank.unsqueeze(0)
|
65 |
+
return fbank
|
66 |
+
|
67 |
+
|
68 |
+
def get_clip_timepoints(clip_sampler, duration):
|
69 |
+
# Read out all clips in this video
|
70 |
+
all_clips_timepoints = []
|
71 |
+
is_last_clip = False
|
72 |
+
end = 0.0
|
73 |
+
while not is_last_clip:
|
74 |
+
start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
|
75 |
+
all_clips_timepoints.append((start, end))
|
76 |
+
return all_clips_timepoints
|
77 |
+
|
78 |
+
|
79 |
+
def load_and_transform_vision_data(image_paths, device):
|
80 |
+
if image_paths is None:
|
81 |
+
return None
|
82 |
+
|
83 |
+
image_ouputs = []
|
84 |
+
for image_path in image_paths:
|
85 |
+
data_transform = transforms.Compose(
|
86 |
+
[
|
87 |
+
transforms.Resize(
|
88 |
+
224, interpolation=transforms.InterpolationMode.BICUBIC
|
89 |
+
),
|
90 |
+
transforms.CenterCrop(224),
|
91 |
+
transforms.ToTensor(),
|
92 |
+
transforms.Normalize(
|
93 |
+
mean=(0.48145466, 0.4578275, 0.40821073),
|
94 |
+
std=(0.26862954, 0.26130258, 0.27577711),
|
95 |
+
),
|
96 |
+
]
|
97 |
+
)
|
98 |
+
with open(image_path, "rb") as fopen:
|
99 |
+
image = Image.open(fopen).convert("RGB")
|
100 |
+
|
101 |
+
image = data_transform(image).to(device)
|
102 |
+
image_ouputs.append(image)
|
103 |
+
return torch.stack(image_ouputs, dim=0)
|
104 |
+
|
105 |
+
|
106 |
+
def load_and_transform_thermal_data(thermal_paths, device):
|
107 |
+
if thermal_paths is None:
|
108 |
+
return None
|
109 |
+
|
110 |
+
thermal_ouputs = []
|
111 |
+
for thermal_path in thermal_paths:
|
112 |
+
data_transform = transforms.Compose(
|
113 |
+
[
|
114 |
+
transforms.Resize(
|
115 |
+
224, interpolation=transforms.InterpolationMode.BICUBIC
|
116 |
+
),
|
117 |
+
transforms.CenterCrop(224),
|
118 |
+
transforms.ToTensor(),
|
119 |
+
]
|
120 |
+
)
|
121 |
+
with open(thermal_path, "rb") as fopen:
|
122 |
+
thermal = Image.open(fopen).convert("L")
|
123 |
+
thermal = data_transform(thermal).to(device)
|
124 |
+
thermal_ouputs.append(thermal)
|
125 |
+
return torch.stack(thermal_ouputs, dim=0)
|
126 |
+
|
127 |
+
|
128 |
+
def load_and_transform_text(text, device):
|
129 |
+
if text is None:
|
130 |
+
return None
|
131 |
+
tokenizer = SimpleTokenizer(bpe_path=BPE_PATH)
|
132 |
+
tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]
|
133 |
+
tokens = torch.cat(tokens, dim=0)
|
134 |
+
return tokens
|
135 |
+
|
136 |
+
|
137 |
+
def load_and_transform_audio_data(
|
138 |
+
audio_paths,
|
139 |
+
device,
|
140 |
+
num_mel_bins=128,
|
141 |
+
target_length=204,
|
142 |
+
sample_rate=16000,
|
143 |
+
clip_duration=2,
|
144 |
+
clips_per_video=3,
|
145 |
+
mean=-4.268,
|
146 |
+
std=9.138,
|
147 |
+
):
|
148 |
+
if audio_paths is None:
|
149 |
+
return None
|
150 |
+
|
151 |
+
audio_outputs = []
|
152 |
+
clip_sampler = ConstantClipsPerVideoSampler(
|
153 |
+
clip_duration=clip_duration, clips_per_video=clips_per_video
|
154 |
+
)
|
155 |
+
|
156 |
+
for audio_path in audio_paths:
|
157 |
+
waveform, sr = torchaudio.load(audio_path)
|
158 |
+
if sample_rate != sr:
|
159 |
+
waveform = torchaudio.functional.resample(
|
160 |
+
waveform, orig_freq=sr, new_freq=sample_rate
|
161 |
+
)
|
162 |
+
all_clips_timepoints = get_clip_timepoints(
|
163 |
+
clip_sampler, waveform.size(1) / sample_rate
|
164 |
+
)
|
165 |
+
all_clips = []
|
166 |
+
for clip_timepoints in all_clips_timepoints:
|
167 |
+
waveform_clip = waveform[
|
168 |
+
:,
|
169 |
+
int(clip_timepoints[0] * sample_rate) : int(
|
170 |
+
clip_timepoints[1] * sample_rate
|
171 |
+
),
|
172 |
+
]
|
173 |
+
waveform_melspec = waveform2melspec(
|
174 |
+
waveform_clip, sample_rate, num_mel_bins, target_length
|
175 |
+
)
|
176 |
+
all_clips.append(waveform_melspec)
|
177 |
+
|
178 |
+
normalize = transforms.Normalize(mean=mean, std=std)
|
179 |
+
all_clips = [normalize(ac).to(device) for ac in all_clips]
|
180 |
+
|
181 |
+
all_clips = torch.stack(all_clips, dim=0)
|
182 |
+
audio_outputs.append(all_clips)
|
183 |
+
|
184 |
+
return torch.stack(audio_outputs, dim=0)
|
185 |
+
|
186 |
+
|
187 |
+
def get_clip_timepoints(clip_sampler, duration):
|
188 |
+
# Read out all clips in this video
|
189 |
+
all_clips_timepoints = []
|
190 |
+
is_last_clip = False
|
191 |
+
end = 0.0
|
192 |
+
while not is_last_clip:
|
193 |
+
start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
|
194 |
+
all_clips_timepoints.append((start, end))
|
195 |
+
return all_clips_timepoints
|
196 |
+
|
197 |
+
|
198 |
+
def crop_boxes(boxes, x_offset, y_offset):
|
199 |
+
"""
|
200 |
+
Peform crop on the bounding boxes given the offsets.
|
201 |
+
Args:
|
202 |
+
boxes (ndarray or None): bounding boxes to peform crop. The dimension
|
203 |
+
is `num boxes` x 4.
|
204 |
+
x_offset (int): cropping offset in the x axis.
|
205 |
+
y_offset (int): cropping offset in the y axis.
|
206 |
+
Returns:
|
207 |
+
cropped_boxes (ndarray or None): the cropped boxes with dimension of
|
208 |
+
`num boxes` x 4.
|
209 |
+
"""
|
210 |
+
cropped_boxes = boxes.copy()
|
211 |
+
cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
|
212 |
+
cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
|
213 |
+
|
214 |
+
return cropped_boxes
|
215 |
+
|
216 |
+
|
217 |
+
def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
|
218 |
+
"""
|
219 |
+
Perform uniform spatial sampling on the images and corresponding boxes.
|
220 |
+
Args:
|
221 |
+
images (tensor): images to perform uniform crop. The dimension is
|
222 |
+
`num frames` x `channel` x `height` x `width`.
|
223 |
+
size (int): size of height and weight to crop the images.
|
224 |
+
spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
|
225 |
+
is larger than height. Or 0, 1, or 2 for top, center, and bottom
|
226 |
+
crop if height is larger than width.
|
227 |
+
boxes (ndarray or None): optional. Corresponding boxes to images.
|
228 |
+
Dimension is `num boxes` x 4.
|
229 |
+
scale_size (int): optinal. If not None, resize the images to scale_size before
|
230 |
+
performing any crop.
|
231 |
+
Returns:
|
232 |
+
cropped (tensor): images with dimension of
|
233 |
+
`num frames` x `channel` x `size` x `size`.
|
234 |
+
cropped_boxes (ndarray or None): the cropped boxes with dimension of
|
235 |
+
`num boxes` x 4.
|
236 |
+
"""
|
237 |
+
assert spatial_idx in [0, 1, 2]
|
238 |
+
ndim = len(images.shape)
|
239 |
+
if ndim == 3:
|
240 |
+
images = images.unsqueeze(0)
|
241 |
+
height = images.shape[2]
|
242 |
+
width = images.shape[3]
|
243 |
+
|
244 |
+
if scale_size is not None:
|
245 |
+
if width <= height:
|
246 |
+
width, height = scale_size, int(height / width * scale_size)
|
247 |
+
else:
|
248 |
+
width, height = int(width / height * scale_size), scale_size
|
249 |
+
images = torch.nn.functional.interpolate(
|
250 |
+
images,
|
251 |
+
size=(height, width),
|
252 |
+
mode="bilinear",
|
253 |
+
align_corners=False,
|
254 |
+
)
|
255 |
+
|
256 |
+
y_offset = int(math.ceil((height - size) / 2))
|
257 |
+
x_offset = int(math.ceil((width - size) / 2))
|
258 |
+
|
259 |
+
if height > width:
|
260 |
+
if spatial_idx == 0:
|
261 |
+
y_offset = 0
|
262 |
+
elif spatial_idx == 2:
|
263 |
+
y_offset = height - size
|
264 |
+
else:
|
265 |
+
if spatial_idx == 0:
|
266 |
+
x_offset = 0
|
267 |
+
elif spatial_idx == 2:
|
268 |
+
x_offset = width - size
|
269 |
+
cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
|
270 |
+
cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
|
271 |
+
if ndim == 3:
|
272 |
+
cropped = cropped.squeeze(0)
|
273 |
+
return cropped, cropped_boxes
|
274 |
+
|
275 |
+
|
276 |
+
class SpatialCrop(nn.Module):
|
277 |
+
"""
|
278 |
+
Convert the video into 3 smaller clips spatially. Must be used after the
|
279 |
+
temporal crops to get spatial crops, and should be used with
|
280 |
+
-2 in the spatial crop at the slowfast augmentation stage (so full
|
281 |
+
frames are passed in here). Will return a larger list with the
|
282 |
+
3x spatial crops as well.
|
283 |
+
"""
|
284 |
+
|
285 |
+
def __init__(self, crop_size: int = 224, num_crops: int = 3):
|
286 |
+
super().__init__()
|
287 |
+
self.crop_size = crop_size
|
288 |
+
if num_crops == 3:
|
289 |
+
self.crops_to_ext = [0, 1, 2]
|
290 |
+
self.flipped_crops_to_ext = []
|
291 |
+
elif num_crops == 1:
|
292 |
+
self.crops_to_ext = [1]
|
293 |
+
self.flipped_crops_to_ext = []
|
294 |
+
else:
|
295 |
+
raise NotImplementedError("Nothing else supported yet")
|
296 |
+
|
297 |
+
def forward(self, videos):
|
298 |
+
"""
|
299 |
+
Args:
|
300 |
+
videos: A list of C, T, H, W videos.
|
301 |
+
Returns:
|
302 |
+
videos: A list with 3x the number of elements. Each video converted
|
303 |
+
to C, T, H', W' by spatial cropping.
|
304 |
+
"""
|
305 |
+
assert isinstance(videos, list), "Must be a list of videos after temporal crops"
|
306 |
+
assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)"
|
307 |
+
res = []
|
308 |
+
for video in videos:
|
309 |
+
for spatial_idx in self.crops_to_ext:
|
310 |
+
res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
|
311 |
+
if not self.flipped_crops_to_ext:
|
312 |
+
continue
|
313 |
+
flipped_video = transforms.functional.hflip(video)
|
314 |
+
for spatial_idx in self.flipped_crops_to_ext:
|
315 |
+
res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
|
316 |
+
return res
|
317 |
+
|
318 |
+
|
319 |
+
def load_and_transform_video_data(
|
320 |
+
video_paths,
|
321 |
+
device,
|
322 |
+
clip_duration=2,
|
323 |
+
clips_per_video=5,
|
324 |
+
sample_rate=16000,
|
325 |
+
):
|
326 |
+
if video_paths is None:
|
327 |
+
return None
|
328 |
+
|
329 |
+
video_outputs = []
|
330 |
+
video_transform = transforms.Compose(
|
331 |
+
[
|
332 |
+
pv_transforms.ShortSideScale(224),
|
333 |
+
NormalizeVideo(
|
334 |
+
mean=(0.48145466, 0.4578275, 0.40821073),
|
335 |
+
std=(0.26862954, 0.26130258, 0.27577711),
|
336 |
+
),
|
337 |
+
]
|
338 |
+
)
|
339 |
+
|
340 |
+
clip_sampler = ConstantClipsPerVideoSampler(
|
341 |
+
clip_duration=clip_duration, clips_per_video=clips_per_video
|
342 |
+
)
|
343 |
+
frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
|
344 |
+
|
345 |
+
for video_path in video_paths:
|
346 |
+
video = EncodedVideo.from_path(
|
347 |
+
video_path,
|
348 |
+
decoder="decord",
|
349 |
+
decode_audio=False,
|
350 |
+
**{"sample_rate": sample_rate},
|
351 |
+
)
|
352 |
+
|
353 |
+
all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
|
354 |
+
|
355 |
+
all_video = []
|
356 |
+
for clip_timepoints in all_clips_timepoints:
|
357 |
+
# Read the clip, get frames
|
358 |
+
clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
|
359 |
+
if clip is None:
|
360 |
+
raise ValueError("No clip found")
|
361 |
+
video_clip = frame_sampler(clip["video"])
|
362 |
+
video_clip = video_clip / 255.0 # since this is float, need 0-1
|
363 |
+
|
364 |
+
all_video.append(video_clip)
|
365 |
+
|
366 |
+
all_video = [video_transform(clip) for clip in all_video]
|
367 |
+
all_video = SpatialCrop(224, num_crops=3)(all_video)
|
368 |
+
|
369 |
+
all_video = torch.stack(all_video, dim=0)
|
370 |
+
video_outputs.append(all_video)
|
371 |
+
|
372 |
+
return torch.stack(video_outputs, dim=0).to(device)
|
model/ImageBind/model_card.md
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Model Card for ImageBind
|
2 |
+
|
3 |
+
Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images.
|
4 |
+
Input any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks.
|
5 |
+
|
6 |
+
# Model Details
|
7 |
+
|
8 |
+
## Model Description
|
9 |
+
|
10 |
+
<!-- Provide a longer summary of what this model is/does. -->
|
11 |
+
Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images
|
12 |
+
|
13 |
+
- **Developed by:** Meta AI
|
14 |
+
- **Model type:** Multimodal model
|
15 |
+
- **Language(s) (NLP):** en
|
16 |
+
- **License:** CC BY-NC-SA 4.0
|
17 |
+
- **Resources for more information:**
|
18 |
+
- [GitHub Repo](https://github.com/facebookresearch/ImageBind)
|
19 |
+
|
20 |
+
|
21 |
+
# Uses
|
22 |
+
|
23 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
24 |
+
This model is intended only for research purposes. It provides a joint embedding space for different modalities -- image/video, text, audio, depth, IMU and thermal images.
|
25 |
+
We hope that these joint embeddings can be used for a variety of different cross-modal research, e.g., cross-modal retrieval and combining embeddings from different modalities.
|
26 |
+
|
27 |
+
## Out-of-Scope Use
|
28 |
+
|
29 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
30 |
+
<!-- If the user enters content, print that. If not, but they enter a task in the list, use that. If neither, say "more info needed." -->
|
31 |
+
|
32 |
+
This model is *NOT* intended to be used in any real world application -- commercial or otherwise.
|
33 |
+
It may produce harmful associations with different inputs.
|
34 |
+
The model needs to be investigated and likely re-trained on specific data for any such application.
|
35 |
+
The model is expected to work better on web-based visual data since it was trained on such data.
|
36 |
+
The text encoder is likely to work only on English language text because of the underlying training datasets.
|
37 |
+
|
38 |
+
# Bias, Risks, and Limitations
|
39 |
+
|
40 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
41 |
+
Open-domain joint embedding models are prone to producing specific biases, e.g., study from [CLIP](https://github.com/openai/CLIP/blob/main/model-card.md#bias-and-fairness).
|
42 |
+
Since our model uses such models as initialization, it will exhibit such biases too.
|
43 |
+
Moreover, for learning joint embeddings for other modalities such as audio, thermal, depth, and IMU we leverage datasets that are relatively small. These joint embeddings are thus limited to the concepts present in the datasets. For example, the thermal datasets we used are limited to outdoor street scenes, while the depth datasets are limited to indoor scenes.
|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
# Training Details
|
48 |
+
|
49 |
+
## Training Data
|
50 |
+
|
51 |
+
<!-- This should link to a Data Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
52 |
+
|
53 |
+
ImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data.
|
54 |
+
In particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder.
|
55 |
+
We train audio embeddings using Audioset, depth embeddings using the SUN RGB-D dataset, IMU using the Ego4D dataset and thermal embeddings using the LLVIP dataset.
|
56 |
+
We provide the exact training data details in the paper.
|
57 |
+
|
58 |
+
|
59 |
+
## Training Procedure
|
60 |
+
|
61 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
62 |
+
Please refer to the research paper and github repo for exact details on this.
|
63 |
+
|
64 |
+
# Evaluation
|
65 |
+
|
66 |
+
## Testing Data, Factors & Metrics
|
67 |
+
|
68 |
+
We evaluate the model on a variety of different classification benchmarks for each modality.
|
69 |
+
The evaluation details are presented in the paper.
|
70 |
+
The models performance is measured using standard classification metrics such as accuracy and mAP.
|
71 |
+
|
72 |
+
# Citation
|
73 |
+
|
74 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
75 |
+
|
76 |
+
**BibTeX:**
|
77 |
+
```
|
78 |
+
@inproceedings{girdhar2023imagebind,
|
79 |
+
title={ImageBind: One Embedding Space To Bind Them All},
|
80 |
+
author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
|
81 |
+
and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
|
82 |
+
booktitle={CVPR},
|
83 |
+
year={2023}
|
84 |
+
}
|
85 |
+
```
|
86 |
+
|
87 |
+
|
88 |
+
# Model Card Contact
|
89 |
+
|
90 |
+
Please reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com
|
91 |
+
|
92 |
+
# How to Get Started with the Model
|
93 |
+
|
94 |
+
Our github repo provides a simple example to extract embeddings from images, audio etc.
|
model/ImageBind/models/__init__.py
ADDED
File without changes
|
model/ImageBind/models/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (160 Bytes). View file
|
|
model/ImageBind/models/__pycache__/helpers.cpython-39.pyc
ADDED
Binary file (5.19 kB). View file
|
|
model/ImageBind/models/__pycache__/imagebind_model.cpython-39.pyc
ADDED
Binary file (8.21 kB). View file
|
|
model/ImageBind/models/__pycache__/multimodal_preprocessors.cpython-39.pyc
ADDED
Binary file (19.9 kB). View file
|
|
model/ImageBind/models/__pycache__/transformer.cpython-39.pyc
ADDED
Binary file (7.88 kB). View file
|
|
model/ImageBind/models/helpers.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
|
3 |
+
# All rights reserved.
|
4 |
+
|
5 |
+
# This source code is licensed under the license found in the
|
6 |
+
# LICENSE file in the root directory of this source tree.
|
7 |
+
|
8 |
+
import math
|
9 |
+
|
10 |
+
import einops
|
11 |
+
import numpy as np
|
12 |
+
import torch
|
13 |
+
|
14 |
+
import torch.nn as nn
|
15 |
+
|
16 |
+
|
17 |
+
class Normalize(nn.Module):
|
18 |
+
def __init__(self, dim: int) -> None:
|
19 |
+
super().__init__()
|
20 |
+
self.dim = dim
|
21 |
+
|
22 |
+
def forward(self, x):
|
23 |
+
return torch.nn.functional.normalize(x, dim=self.dim, p=2)
|
24 |
+
|
25 |
+
|
26 |
+
class LearnableLogitScaling(nn.Module):
|
27 |
+
def __init__(
|
28 |
+
self,
|
29 |
+
logit_scale_init: float = 1 / 0.07,
|
30 |
+
learnable: bool = True,
|
31 |
+
max_logit_scale: float = 100,
|
32 |
+
) -> None:
|
33 |
+
super().__init__()
|
34 |
+
self.max_logit_scale = max_logit_scale
|
35 |
+
self.logit_scale_init = logit_scale_init
|
36 |
+
self.learnable = learnable
|
37 |
+
log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init)
|
38 |
+
if learnable:
|
39 |
+
self.log_logit_scale = nn.Parameter(log_logit_scale)
|
40 |
+
else:
|
41 |
+
self.register_buffer("log_logit_scale", log_logit_scale)
|
42 |
+
|
43 |
+
def forward(self, x):
|
44 |
+
return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x
|
45 |
+
|
46 |
+
def extra_repr(self):
|
47 |
+
st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}, max_logit_scale={self.max_logit_scale}"
|
48 |
+
return st
|
49 |
+
|
50 |
+
|
51 |
+
class EinOpsRearrange(nn.Module):
|
52 |
+
def __init__(self, rearrange_expr: str, **kwargs) -> None:
|
53 |
+
super().__init__()
|
54 |
+
self.rearrange_expr = rearrange_expr
|
55 |
+
self.kwargs = kwargs
|
56 |
+
|
57 |
+
def forward(self, x):
|
58 |
+
assert isinstance(x, torch.Tensor)
|
59 |
+
return einops.rearrange(x, self.rearrange_expr, **self.kwargs)
|
60 |
+
|
61 |
+
|
62 |
+
class VerboseNNModule(nn.Module):
|
63 |
+
"""
|
64 |
+
Wrapper around nn.Module that prints registered buffers and parameter names.
|
65 |
+
"""
|
66 |
+
|
67 |
+
@staticmethod
|
68 |
+
def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str:
|
69 |
+
st = (
|
70 |
+
"("
|
71 |
+
+ name
|
72 |
+
+ "): "
|
73 |
+
+ "tensor("
|
74 |
+
+ str(tuple(tensor[1].shape))
|
75 |
+
+ ", requires_grad="
|
76 |
+
+ str(tensor[1].requires_grad)
|
77 |
+
+ ")\n"
|
78 |
+
)
|
79 |
+
return st
|
80 |
+
|
81 |
+
def extra_repr(self) -> str:
|
82 |
+
named_modules = set()
|
83 |
+
for p in self.named_modules():
|
84 |
+
named_modules.update([p[0]])
|
85 |
+
named_modules = list(named_modules)
|
86 |
+
|
87 |
+
string_repr = ""
|
88 |
+
for p in self.named_parameters():
|
89 |
+
name = p[0].split(".")[0]
|
90 |
+
if name not in named_modules:
|
91 |
+
string_repr += self.get_readable_tensor_repr(name, p)
|
92 |
+
|
93 |
+
for p in self.named_buffers():
|
94 |
+
name = p[0].split(".")[0]
|
95 |
+
string_repr += self.get_readable_tensor_repr(name, p)
|
96 |
+
|
97 |
+
return string_repr
|
98 |
+
|
99 |
+
|
100 |
+
def cast_if_src_dtype(
|
101 |
+
tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype
|
102 |
+
):
|
103 |
+
updated = False
|
104 |
+
if tensor.dtype == src_dtype:
|
105 |
+
tensor = tensor.to(dtype=tgt_dtype)
|
106 |
+
updated = True
|
107 |
+
return tensor, updated
|
108 |
+
|
109 |
+
|
110 |
+
class QuickGELU(nn.Module):
|
111 |
+
# From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166
|
112 |
+
def forward(self, x: torch.Tensor):
|
113 |
+
return x * torch.sigmoid(1.702 * x)
|
114 |
+
|
115 |
+
|
116 |
+
class SelectElement(nn.Module):
|
117 |
+
def __init__(self, index) -> None:
|
118 |
+
super().__init__()
|
119 |
+
self.index = index
|
120 |
+
|
121 |
+
def forward(self, x):
|
122 |
+
assert x.ndim >= 3
|
123 |
+
return x[:, self.index, ...]
|
124 |
+
|
125 |
+
|
126 |
+
class SelectEOSAndProject(nn.Module):
|
127 |
+
"""
|
128 |
+
Text Pooling used in OpenCLIP
|
129 |
+
"""
|
130 |
+
|
131 |
+
def __init__(self, proj: nn.Module) -> None:
|
132 |
+
super().__init__()
|
133 |
+
self.proj = proj
|
134 |
+
|
135 |
+
def forward(self, x, seq_len):
|
136 |
+
assert x.ndim == 3
|
137 |
+
# x is of shape B x L x D
|
138 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
139 |
+
x = x[torch.arange(x.shape[0]), seq_len]
|
140 |
+
x = self.proj(x)
|
141 |
+
return x
|
model/ImageBind/models/imagebind_model.py
ADDED
@@ -0,0 +1,521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
|
3 |
+
# All rights reserved.
|
4 |
+
|
5 |
+
# This source code is licensed under the license found in the
|
6 |
+
# LICENSE file in the root directory of this source tree.
|
7 |
+
|
8 |
+
|
9 |
+
import os
|
10 |
+
import urllib
|
11 |
+
from functools import partial
|
12 |
+
from types import SimpleNamespace
|
13 |
+
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
|
17 |
+
from .helpers import (
|
18 |
+
EinOpsRearrange,
|
19 |
+
LearnableLogitScaling,
|
20 |
+
Normalize,
|
21 |
+
SelectElement,
|
22 |
+
SelectEOSAndProject,
|
23 |
+
)
|
24 |
+
from .multimodal_preprocessors import (
|
25 |
+
AudioPreprocessor,
|
26 |
+
IMUPreprocessor,
|
27 |
+
PadIm2Video,
|
28 |
+
PatchEmbedGeneric,
|
29 |
+
RGBDTPreprocessor,
|
30 |
+
SpatioTemporalPosEmbeddingHelper,
|
31 |
+
TextPreprocessor,
|
32 |
+
ThermalPreprocessor,
|
33 |
+
)
|
34 |
+
|
35 |
+
from .transformer import MultiheadAttention, SimpleTransformer
|
36 |
+
|
37 |
+
|
38 |
+
ModalityType = SimpleNamespace(
|
39 |
+
VISION="vision",
|
40 |
+
TEXT="text",
|
41 |
+
AUDIO="audio",
|
42 |
+
THERMAL="thermal",
|
43 |
+
DEPTH="depth",
|
44 |
+
IMU="imu",
|
45 |
+
)
|
46 |
+
|
47 |
+
|
48 |
+
class ImageBindModel(nn.Module):
|
49 |
+
def __init__(
|
50 |
+
self,
|
51 |
+
video_frames=2,
|
52 |
+
kernel_size=(2, 14, 14),
|
53 |
+
audio_kernel_size=16,
|
54 |
+
audio_stride=10,
|
55 |
+
out_embed_dim=768,
|
56 |
+
vision_embed_dim=1024,
|
57 |
+
vision_num_blocks=24,
|
58 |
+
vision_num_heads=16,
|
59 |
+
audio_embed_dim=768,
|
60 |
+
audio_num_blocks=12,
|
61 |
+
audio_num_heads=12,
|
62 |
+
audio_num_mel_bins=128,
|
63 |
+
audio_target_len=204,
|
64 |
+
audio_drop_path=0.1,
|
65 |
+
text_embed_dim=768,
|
66 |
+
text_num_blocks=12,
|
67 |
+
text_num_heads=12,
|
68 |
+
depth_embed_dim=384,
|
69 |
+
depth_kernel_size=16,
|
70 |
+
depth_num_blocks=12,
|
71 |
+
depth_num_heads=8,
|
72 |
+
depth_drop_path=0.0,
|
73 |
+
thermal_embed_dim=768,
|
74 |
+
thermal_kernel_size=16,
|
75 |
+
thermal_num_blocks=12,
|
76 |
+
thermal_num_heads=12,
|
77 |
+
thermal_drop_path=0.0,
|
78 |
+
imu_embed_dim=512,
|
79 |
+
imu_kernel_size=8,
|
80 |
+
imu_num_blocks=6,
|
81 |
+
imu_num_heads=8,
|
82 |
+
imu_drop_path=0.7,
|
83 |
+
):
|
84 |
+
super().__init__()
|
85 |
+
|
86 |
+
self.modality_preprocessors = self._create_modality_preprocessors(
|
87 |
+
video_frames,
|
88 |
+
vision_embed_dim,
|
89 |
+
kernel_size,
|
90 |
+
text_embed_dim,
|
91 |
+
audio_embed_dim,
|
92 |
+
audio_kernel_size,
|
93 |
+
audio_stride,
|
94 |
+
audio_num_mel_bins,
|
95 |
+
audio_target_len,
|
96 |
+
depth_embed_dim,
|
97 |
+
depth_kernel_size,
|
98 |
+
thermal_embed_dim,
|
99 |
+
thermal_kernel_size,
|
100 |
+
imu_embed_dim,
|
101 |
+
)
|
102 |
+
|
103 |
+
self.modality_trunks = self._create_modality_trunks(
|
104 |
+
vision_embed_dim,
|
105 |
+
vision_num_blocks,
|
106 |
+
vision_num_heads,
|
107 |
+
text_embed_dim,
|
108 |
+
text_num_blocks,
|
109 |
+
text_num_heads,
|
110 |
+
audio_embed_dim,
|
111 |
+
audio_num_blocks,
|
112 |
+
audio_num_heads,
|
113 |
+
audio_drop_path,
|
114 |
+
depth_embed_dim,
|
115 |
+
depth_num_blocks,
|
116 |
+
depth_num_heads,
|
117 |
+
depth_drop_path,
|
118 |
+
thermal_embed_dim,
|
119 |
+
thermal_num_blocks,
|
120 |
+
thermal_num_heads,
|
121 |
+
thermal_drop_path,
|
122 |
+
imu_embed_dim,
|
123 |
+
imu_num_blocks,
|
124 |
+
imu_num_heads,
|
125 |
+
imu_drop_path,
|
126 |
+
)
|
127 |
+
|
128 |
+
self.modality_heads = self._create_modality_heads(
|
129 |
+
out_embed_dim,
|
130 |
+
vision_embed_dim,
|
131 |
+
text_embed_dim,
|
132 |
+
audio_embed_dim,
|
133 |
+
depth_embed_dim,
|
134 |
+
thermal_embed_dim,
|
135 |
+
imu_embed_dim,
|
136 |
+
)
|
137 |
+
|
138 |
+
self.modality_postprocessors = self._create_modality_postprocessors(
|
139 |
+
out_embed_dim
|
140 |
+
)
|
141 |
+
|
142 |
+
def _create_modality_preprocessors(
|
143 |
+
self,
|
144 |
+
video_frames=2,
|
145 |
+
vision_embed_dim=1024,
|
146 |
+
kernel_size=(2, 14, 14),
|
147 |
+
text_embed_dim=768,
|
148 |
+
audio_embed_dim=768,
|
149 |
+
audio_kernel_size=16,
|
150 |
+
audio_stride=10,
|
151 |
+
audio_num_mel_bins=128,
|
152 |
+
audio_target_len=204,
|
153 |
+
depth_embed_dim=768,
|
154 |
+
depth_kernel_size=16,
|
155 |
+
thermal_embed_dim=768,
|
156 |
+
thermal_kernel_size=16,
|
157 |
+
imu_embed_dim=512,
|
158 |
+
):
|
159 |
+
rgbt_stem = PatchEmbedGeneric(
|
160 |
+
proj_stem=[
|
161 |
+
PadIm2Video(pad_type="repeat", ntimes=2),
|
162 |
+
nn.Conv3d(
|
163 |
+
in_channels=3,
|
164 |
+
kernel_size=kernel_size,
|
165 |
+
out_channels=vision_embed_dim,
|
166 |
+
stride=kernel_size,
|
167 |
+
bias=False,
|
168 |
+
),
|
169 |
+
]
|
170 |
+
)
|
171 |
+
rgbt_preprocessor = RGBDTPreprocessor(
|
172 |
+
img_size=[3, video_frames, 224, 224],
|
173 |
+
num_cls_tokens=1,
|
174 |
+
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
|
175 |
+
rgbt_stem=rgbt_stem,
|
176 |
+
depth_stem=None,
|
177 |
+
)
|
178 |
+
|
179 |
+
text_preprocessor = TextPreprocessor(
|
180 |
+
context_length=77,
|
181 |
+
vocab_size=49408,
|
182 |
+
embed_dim=text_embed_dim,
|
183 |
+
causal_masking=True,
|
184 |
+
)
|
185 |
+
|
186 |
+
audio_stem = PatchEmbedGeneric(
|
187 |
+
proj_stem=[
|
188 |
+
nn.Conv2d(
|
189 |
+
in_channels=1,
|
190 |
+
kernel_size=audio_kernel_size,
|
191 |
+
stride=audio_stride,
|
192 |
+
out_channels=audio_embed_dim,
|
193 |
+
bias=False,
|
194 |
+
),
|
195 |
+
],
|
196 |
+
norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim),
|
197 |
+
)
|
198 |
+
audio_preprocessor = AudioPreprocessor(
|
199 |
+
img_size=[1, audio_num_mel_bins, audio_target_len],
|
200 |
+
num_cls_tokens=1,
|
201 |
+
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
|
202 |
+
audio_stem=audio_stem,
|
203 |
+
)
|
204 |
+
|
205 |
+
depth_stem = PatchEmbedGeneric(
|
206 |
+
[
|
207 |
+
nn.Conv2d(
|
208 |
+
kernel_size=depth_kernel_size,
|
209 |
+
in_channels=1,
|
210 |
+
out_channels=depth_embed_dim,
|
211 |
+
stride=depth_kernel_size,
|
212 |
+
bias=False,
|
213 |
+
),
|
214 |
+
],
|
215 |
+
norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim),
|
216 |
+
)
|
217 |
+
|
218 |
+
depth_preprocessor = RGBDTPreprocessor(
|
219 |
+
img_size=[1, 224, 224],
|
220 |
+
num_cls_tokens=1,
|
221 |
+
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
|
222 |
+
rgbt_stem=None,
|
223 |
+
depth_stem=depth_stem,
|
224 |
+
)
|
225 |
+
|
226 |
+
thermal_stem = PatchEmbedGeneric(
|
227 |
+
[
|
228 |
+
nn.Conv2d(
|
229 |
+
kernel_size=thermal_kernel_size,
|
230 |
+
in_channels=1,
|
231 |
+
out_channels=thermal_embed_dim,
|
232 |
+
stride=thermal_kernel_size,
|
233 |
+
bias=False,
|
234 |
+
),
|
235 |
+
],
|
236 |
+
norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim),
|
237 |
+
)
|
238 |
+
thermal_preprocessor = ThermalPreprocessor(
|
239 |
+
img_size=[1, 224, 224],
|
240 |
+
num_cls_tokens=1,
|
241 |
+
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
|
242 |
+
thermal_stem=thermal_stem,
|
243 |
+
)
|
244 |
+
|
245 |
+
imu_stem = PatchEmbedGeneric(
|
246 |
+
[
|
247 |
+
nn.Linear(
|
248 |
+
in_features=48,
|
249 |
+
out_features=imu_embed_dim,
|
250 |
+
bias=False,
|
251 |
+
),
|
252 |
+
],
|
253 |
+
norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim),
|
254 |
+
)
|
255 |
+
|
256 |
+
imu_preprocessor = IMUPreprocessor(
|
257 |
+
img_size=[6, 2000],
|
258 |
+
num_cls_tokens=1,
|
259 |
+
kernel_size=8,
|
260 |
+
embed_dim=imu_embed_dim,
|
261 |
+
pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
|
262 |
+
imu_stem=imu_stem,
|
263 |
+
)
|
264 |
+
|
265 |
+
modality_preprocessors = {
|
266 |
+
ModalityType.VISION: rgbt_preprocessor,
|
267 |
+
ModalityType.TEXT: text_preprocessor,
|
268 |
+
ModalityType.AUDIO: audio_preprocessor,
|
269 |
+
ModalityType.DEPTH: depth_preprocessor,
|
270 |
+
ModalityType.THERMAL: thermal_preprocessor,
|
271 |
+
ModalityType.IMU: imu_preprocessor,
|
272 |
+
}
|
273 |
+
|
274 |
+
return nn.ModuleDict(modality_preprocessors)
|
275 |
+
|
276 |
+
def _create_modality_trunks(
|
277 |
+
self,
|
278 |
+
vision_embed_dim=1024,
|
279 |
+
vision_num_blocks=24,
|
280 |
+
vision_num_heads=16,
|
281 |
+
text_embed_dim=768,
|
282 |
+
text_num_blocks=12,
|
283 |
+
text_num_heads=12,
|
284 |
+
audio_embed_dim=768,
|
285 |
+
audio_num_blocks=12,
|
286 |
+
audio_num_heads=12,
|
287 |
+
audio_drop_path=0.0,
|
288 |
+
depth_embed_dim=768,
|
289 |
+
depth_num_blocks=12,
|
290 |
+
depth_num_heads=12,
|
291 |
+
depth_drop_path=0.0,
|
292 |
+
thermal_embed_dim=768,
|
293 |
+
thermal_num_blocks=12,
|
294 |
+
thermal_num_heads=12,
|
295 |
+
thermal_drop_path=0.0,
|
296 |
+
imu_embed_dim=512,
|
297 |
+
imu_num_blocks=6,
|
298 |
+
imu_num_heads=8,
|
299 |
+
imu_drop_path=0.7,
|
300 |
+
):
|
301 |
+
def instantiate_trunk(
|
302 |
+
embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path
|
303 |
+
):
|
304 |
+
return SimpleTransformer(
|
305 |
+
embed_dim=embed_dim,
|
306 |
+
num_blocks=num_blocks,
|
307 |
+
ffn_dropout_rate=0.0,
|
308 |
+
drop_path_rate=drop_path,
|
309 |
+
attn_target=partial(
|
310 |
+
MultiheadAttention,
|
311 |
+
embed_dim=embed_dim,
|
312 |
+
num_heads=num_heads,
|
313 |
+
bias=True,
|
314 |
+
add_bias_kv=add_bias_kv,
|
315 |
+
),
|
316 |
+
pre_transformer_layer=nn.Sequential(
|
317 |
+
nn.LayerNorm(embed_dim, eps=1e-6)
|
318 |
+
if pre_transformer_ln
|
319 |
+
else nn.Identity(),
|
320 |
+
EinOpsRearrange("b l d -> l b d"),
|
321 |
+
),
|
322 |
+
post_transformer_layer=EinOpsRearrange("l b d -> b l d"),
|
323 |
+
)
|
324 |
+
|
325 |
+
modality_trunks = {}
|
326 |
+
modality_trunks[ModalityType.VISION] = instantiate_trunk(
|
327 |
+
vision_embed_dim,
|
328 |
+
vision_num_blocks,
|
329 |
+
vision_num_heads,
|
330 |
+
pre_transformer_ln=True,
|
331 |
+
add_bias_kv=False,
|
332 |
+
drop_path=0.0,
|
333 |
+
)
|
334 |
+
modality_trunks[ModalityType.TEXT] = instantiate_trunk(
|
335 |
+
text_embed_dim,
|
336 |
+
text_num_blocks,
|
337 |
+
text_num_heads,
|
338 |
+
pre_transformer_ln=False,
|
339 |
+
add_bias_kv=False,
|
340 |
+
drop_path=0.0,
|
341 |
+
)
|
342 |
+
modality_trunks[ModalityType.AUDIO] = instantiate_trunk(
|
343 |
+
audio_embed_dim,
|
344 |
+
audio_num_blocks,
|
345 |
+
audio_num_heads,
|
346 |
+
pre_transformer_ln=False,
|
347 |
+
add_bias_kv=True,
|
348 |
+
drop_path=audio_drop_path,
|
349 |
+
)
|
350 |
+
modality_trunks[ModalityType.DEPTH] = instantiate_trunk(
|
351 |
+
depth_embed_dim,
|
352 |
+
depth_num_blocks,
|
353 |
+
depth_num_heads,
|
354 |
+
pre_transformer_ln=False,
|
355 |
+
add_bias_kv=True,
|
356 |
+
drop_path=depth_drop_path,
|
357 |
+
)
|
358 |
+
modality_trunks[ModalityType.THERMAL] = instantiate_trunk(
|
359 |
+
thermal_embed_dim,
|
360 |
+
thermal_num_blocks,
|
361 |
+
thermal_num_heads,
|
362 |
+
pre_transformer_ln=False,
|
363 |
+
add_bias_kv=True,
|
364 |
+
drop_path=thermal_drop_path,
|
365 |
+
)
|
366 |
+
modality_trunks[ModalityType.IMU] = instantiate_trunk(
|
367 |
+
imu_embed_dim,
|
368 |
+
imu_num_blocks,
|
369 |
+
imu_num_heads,
|
370 |
+
pre_transformer_ln=False,
|
371 |
+
add_bias_kv=True,
|
372 |
+
drop_path=imu_drop_path,
|
373 |
+
)
|
374 |
+
|
375 |
+
return nn.ModuleDict(modality_trunks)
|
376 |
+
|
377 |
+
def _create_modality_heads(
|
378 |
+
self,
|
379 |
+
out_embed_dim,
|
380 |
+
vision_embed_dim,
|
381 |
+
text_embed_dim,
|
382 |
+
audio_embed_dim,
|
383 |
+
depth_embed_dim,
|
384 |
+
thermal_embed_dim,
|
385 |
+
imu_embed_dim,
|
386 |
+
):
|
387 |
+
modality_heads = {}
|
388 |
+
|
389 |
+
modality_heads[ModalityType.VISION] = nn.Sequential(
|
390 |
+
nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6),
|
391 |
+
SelectElement(index=0),
|
392 |
+
nn.Linear(vision_embed_dim, out_embed_dim, bias=False),
|
393 |
+
)
|
394 |
+
|
395 |
+
modality_heads[ModalityType.TEXT] = SelectEOSAndProject(
|
396 |
+
proj=nn.Sequential(
|
397 |
+
nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6),
|
398 |
+
nn.Linear(text_embed_dim, out_embed_dim, bias=False),
|
399 |
+
)
|
400 |
+
)
|
401 |
+
|
402 |
+
modality_heads[ModalityType.AUDIO] = nn.Sequential(
|
403 |
+
nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6),
|
404 |
+
SelectElement(index=0),
|
405 |
+
nn.Linear(audio_embed_dim, out_embed_dim, bias=False),
|
406 |
+
)
|
407 |
+
|
408 |
+
modality_heads[ModalityType.DEPTH] = nn.Sequential(
|
409 |
+
nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6),
|
410 |
+
SelectElement(index=0),
|
411 |
+
nn.Linear(depth_embed_dim, out_embed_dim, bias=False),
|
412 |
+
)
|
413 |
+
|
414 |
+
modality_heads[ModalityType.THERMAL] = nn.Sequential(
|
415 |
+
nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6),
|
416 |
+
SelectElement(index=0),
|
417 |
+
nn.Linear(thermal_embed_dim, out_embed_dim, bias=False),
|
418 |
+
)
|
419 |
+
|
420 |
+
modality_heads[ModalityType.IMU] = nn.Sequential(
|
421 |
+
nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6),
|
422 |
+
SelectElement(index=0),
|
423 |
+
nn.Dropout(p=0.5),
|
424 |
+
nn.Linear(imu_embed_dim, out_embed_dim, bias=False),
|
425 |
+
)
|
426 |
+
|
427 |
+
return nn.ModuleDict(modality_heads)
|
428 |
+
|
429 |
+
def _create_modality_postprocessors(self, out_embed_dim):
|
430 |
+
modality_postprocessors = {}
|
431 |
+
|
432 |
+
modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1)
|
433 |
+
modality_postprocessors[ModalityType.TEXT] = nn.Sequential(
|
434 |
+
Normalize(dim=-1), LearnableLogitScaling(learnable=True)
|
435 |
+
)
|
436 |
+
modality_postprocessors[ModalityType.AUDIO] = nn.Sequential(
|
437 |
+
Normalize(dim=-1),
|
438 |
+
LearnableLogitScaling(logit_scale_init=20.0, learnable=False),
|
439 |
+
)
|
440 |
+
modality_postprocessors[ModalityType.DEPTH] = nn.Sequential(
|
441 |
+
Normalize(dim=-1),
|
442 |
+
LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
|
443 |
+
)
|
444 |
+
modality_postprocessors[ModalityType.THERMAL] = nn.Sequential(
|
445 |
+
Normalize(dim=-1),
|
446 |
+
LearnableLogitScaling(logit_scale_init=10.0, learnable=False),
|
447 |
+
)
|
448 |
+
modality_postprocessors[ModalityType.IMU] = nn.Sequential(
|
449 |
+
Normalize(dim=-1),
|
450 |
+
LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
|
451 |
+
)
|
452 |
+
return nn.ModuleDict(modality_postprocessors)
|
453 |
+
|
454 |
+
def forward(self, inputs):
|
455 |
+
outputs = {}
|
456 |
+
for modality_key, modality_value in inputs.items():
|
457 |
+
reduce_list = (
|
458 |
+
modality_value.ndim >= 5
|
459 |
+
) # Audio and Video inputs consist of multiple clips
|
460 |
+
if reduce_list:
|
461 |
+
B, S = modality_value.shape[:2]
|
462 |
+
modality_value = modality_value.reshape(
|
463 |
+
B * S, *modality_value.shape[2:]
|
464 |
+
)
|
465 |
+
|
466 |
+
if modality_value is not None:
|
467 |
+
modality_value = self.modality_preprocessors[modality_key](
|
468 |
+
**{modality_key: modality_value}
|
469 |
+
)
|
470 |
+
trunk_inputs = modality_value["trunk"]
|
471 |
+
head_inputs = modality_value["head"]
|
472 |
+
modality_value = self.modality_trunks[modality_key](**trunk_inputs)
|
473 |
+
modality_value = self.modality_heads[modality_key](
|
474 |
+
modality_value, **head_inputs
|
475 |
+
)
|
476 |
+
if modality_key in [ModalityType.AUDIO]:
|
477 |
+
modality_value = self.modality_postprocessors[modality_key][0](
|
478 |
+
modality_value
|
479 |
+
)
|
480 |
+
else:
|
481 |
+
modality_value = self.modality_postprocessors[modality_key](
|
482 |
+
modality_value
|
483 |
+
)
|
484 |
+
|
485 |
+
if reduce_list:
|
486 |
+
modality_value = modality_value.reshape(B, S, -1)
|
487 |
+
modality_value = modality_value.mean(dim=1)
|
488 |
+
|
489 |
+
outputs[modality_key] = modality_value
|
490 |
+
|
491 |
+
return outputs
|
492 |
+
|
493 |
+
|
494 |
+
def imagebind_huge(pretrained=False, store_path=r'.checkpoints'):
|
495 |
+
model = ImageBindModel(
|
496 |
+
vision_embed_dim=1280,
|
497 |
+
vision_num_blocks=32,
|
498 |
+
vision_num_heads=16,
|
499 |
+
text_embed_dim=1024,
|
500 |
+
text_num_blocks=24,
|
501 |
+
text_num_heads=16,
|
502 |
+
out_embed_dim=1024,
|
503 |
+
audio_drop_path=0.1,
|
504 |
+
imu_drop_path=0.7,
|
505 |
+
)
|
506 |
+
|
507 |
+
if pretrained:
|
508 |
+
if not os.path.exists("{}/imagebind_huge.pth".format(store_path)):
|
509 |
+
print(
|
510 |
+
"Downloading imagebind weights to {}/imagebind_huge.pth ...".format(store_path)
|
511 |
+
)
|
512 |
+
os.makedirs(store_path, exist_ok=True)
|
513 |
+
torch.hub.download_url_to_file(
|
514 |
+
"https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth",
|
515 |
+
"{}/imagebind_huge.pth".format(store_path),
|
516 |
+
progress=True,
|
517 |
+
)
|
518 |
+
|
519 |
+
model.load_state_dict(torch.load("{}/imagebind_huge.pth".format(store_path)))
|
520 |
+
|
521 |
+
return model, 1024
|
model/ImageBind/models/multimodal_preprocessors.py
ADDED
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
|
3 |
+
# All rights reserved.
|
4 |
+
|
5 |
+
# This source code is licensed under the license found in the
|
6 |
+
# LICENSE file in the root directory of this source tree.
|
7 |
+
|
8 |
+
import gzip
|
9 |
+
import html
|
10 |
+
import io
|
11 |
+
import math
|
12 |
+
from functools import lru_cache
|
13 |
+
from typing import Callable, List, Optional
|
14 |
+
|
15 |
+
import ftfy
|
16 |
+
|
17 |
+
import numpy as np
|
18 |
+
import regex as re
|
19 |
+
import torch
|
20 |
+
import torch.nn as nn
|
21 |
+
from iopath.common.file_io import g_pathmgr
|
22 |
+
from timm.models.layers import trunc_normal_
|
23 |
+
|
24 |
+
from .helpers import cast_if_src_dtype, VerboseNNModule
|
25 |
+
|
26 |
+
|
27 |
+
def get_sinusoid_encoding_table(n_position, d_hid):
|
28 |
+
"""Sinusoid position encoding table"""
|
29 |
+
|
30 |
+
# TODO: make it with torch instead of numpy
|
31 |
+
def get_position_angle_vec(position):
|
32 |
+
return [
|
33 |
+
position / np.power(10000, 2 * (hid_j // 2) / d_hid)
|
34 |
+
for hid_j in range(d_hid)
|
35 |
+
]
|
36 |
+
|
37 |
+
sinusoid_table = np.array(
|
38 |
+
[get_position_angle_vec(pos_i) for pos_i in range(n_position)]
|
39 |
+
)
|
40 |
+
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
|
41 |
+
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
|
42 |
+
|
43 |
+
return torch.FloatTensor(sinusoid_table).unsqueeze(0)
|
44 |
+
|
45 |
+
|
46 |
+
def interpolate_pos_encoding_2d(target_spatial_size, pos_embed):
|
47 |
+
N = pos_embed.shape[1]
|
48 |
+
if N == target_spatial_size:
|
49 |
+
return pos_embed
|
50 |
+
dim = pos_embed.shape[-1]
|
51 |
+
# nn.functional.interpolate doesn't work with bfloat16 so we cast to float32
|
52 |
+
pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32)
|
53 |
+
pos_embed = nn.functional.interpolate(
|
54 |
+
pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(
|
55 |
+
0, 3, 1, 2
|
56 |
+
),
|
57 |
+
scale_factor=math.sqrt(target_spatial_size / N),
|
58 |
+
mode="bicubic",
|
59 |
+
)
|
60 |
+
if updated:
|
61 |
+
pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16)
|
62 |
+
pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
63 |
+
return pos_embed
|
64 |
+
|
65 |
+
|
66 |
+
def interpolate_pos_encoding(
|
67 |
+
npatch_per_img,
|
68 |
+
pos_embed,
|
69 |
+
patches_layout,
|
70 |
+
input_shape=None,
|
71 |
+
first_patch_idx=1,
|
72 |
+
):
|
73 |
+
assert first_patch_idx == 0 or first_patch_idx == 1, "there is 1 CLS token or none"
|
74 |
+
N = pos_embed.shape[1] - first_patch_idx # since it's 1 if cls_token exists
|
75 |
+
if npatch_per_img == N:
|
76 |
+
return pos_embed
|
77 |
+
|
78 |
+
assert (
|
79 |
+
patches_layout[-1] == patches_layout[-2]
|
80 |
+
), "Interpolation of pos embed not supported for non-square layouts"
|
81 |
+
|
82 |
+
class_emb = pos_embed[:, :first_patch_idx]
|
83 |
+
pos_embed = pos_embed[:, first_patch_idx:]
|
84 |
+
|
85 |
+
if input_shape is None or patches_layout[0] == 1:
|
86 |
+
# simple 2D pos embedding, no temporal component
|
87 |
+
pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed)
|
88 |
+
elif patches_layout[0] > 1:
|
89 |
+
# pos embed has a temporal component
|
90 |
+
assert len(input_shape) == 4, "temporal interpolation not supported"
|
91 |
+
# we only support 2D interpolation in this case
|
92 |
+
num_frames = patches_layout[0]
|
93 |
+
num_spatial_tokens = patches_layout[1] * patches_layout[2]
|
94 |
+
pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1)
|
95 |
+
# interpolate embedding for zeroth frame
|
96 |
+
pos_embed = interpolate_pos_encoding_2d(
|
97 |
+
npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0)
|
98 |
+
)
|
99 |
+
else:
|
100 |
+
raise ValueError("This type of interpolation isn't implemented")
|
101 |
+
|
102 |
+
return torch.cat((class_emb, pos_embed), dim=1)
|
103 |
+
|
104 |
+
|
105 |
+
def _get_pos_embedding(
|
106 |
+
npatch_per_img,
|
107 |
+
pos_embed,
|
108 |
+
patches_layout,
|
109 |
+
input_shape,
|
110 |
+
first_patch_idx=1,
|
111 |
+
):
|
112 |
+
pos_embed = interpolate_pos_encoding(
|
113 |
+
npatch_per_img,
|
114 |
+
pos_embed,
|
115 |
+
patches_layout,
|
116 |
+
input_shape=input_shape,
|
117 |
+
first_patch_idx=first_patch_idx,
|
118 |
+
)
|
119 |
+
return pos_embed
|
120 |
+
|
121 |
+
|
122 |
+
class PatchEmbedGeneric(nn.Module):
|
123 |
+
"""
|
124 |
+
PatchEmbed from Hydra
|
125 |
+
"""
|
126 |
+
|
127 |
+
def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None):
|
128 |
+
super().__init__()
|
129 |
+
|
130 |
+
if len(proj_stem) > 1:
|
131 |
+
self.proj = nn.Sequential(*proj_stem)
|
132 |
+
else:
|
133 |
+
# Special case to be able to load pre-trained models that were
|
134 |
+
# trained with a standard stem
|
135 |
+
self.proj = proj_stem[0]
|
136 |
+
self.norm_layer = norm_layer
|
137 |
+
|
138 |
+
def get_patch_layout(self, img_size):
|
139 |
+
with torch.no_grad():
|
140 |
+
dummy_img = torch.zeros(
|
141 |
+
[
|
142 |
+
1,
|
143 |
+
]
|
144 |
+
+ img_size
|
145 |
+
)
|
146 |
+
dummy_out = self.proj(dummy_img)
|
147 |
+
embed_dim = dummy_out.shape[1]
|
148 |
+
patches_layout = tuple(dummy_out.shape[2:])
|
149 |
+
num_patches = np.prod(patches_layout)
|
150 |
+
return patches_layout, num_patches, embed_dim
|
151 |
+
|
152 |
+
def forward(self, x):
|
153 |
+
x = self.proj(x)
|
154 |
+
# B C (T) H W -> B (T)HW C
|
155 |
+
x = x.flatten(2).transpose(1, 2)
|
156 |
+
if self.norm_layer is not None:
|
157 |
+
x = self.norm_layer(x)
|
158 |
+
return x
|
159 |
+
|
160 |
+
|
161 |
+
class SpatioTemporalPosEmbeddingHelper(VerboseNNModule):
|
162 |
+
def __init__(
|
163 |
+
self,
|
164 |
+
patches_layout: List,
|
165 |
+
num_patches: int,
|
166 |
+
num_cls_tokens: int,
|
167 |
+
embed_dim: int,
|
168 |
+
learnable: bool,
|
169 |
+
) -> None:
|
170 |
+
super().__init__()
|
171 |
+
self.num_cls_tokens = num_cls_tokens
|
172 |
+
self.patches_layout = patches_layout
|
173 |
+
self.num_patches = num_patches
|
174 |
+
self.num_tokens = num_cls_tokens + num_patches
|
175 |
+
self.learnable = learnable
|
176 |
+
if self.learnable:
|
177 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))
|
178 |
+
trunc_normal_(self.pos_embed, std=0.02)
|
179 |
+
else:
|
180 |
+
self.register_buffer(
|
181 |
+
"pos_embed", get_sinusoid_encoding_table(self.num_tokens, embed_dim)
|
182 |
+
)
|
183 |
+
|
184 |
+
def get_pos_embedding(self, vision_input, all_vision_tokens):
|
185 |
+
input_shape = vision_input.shape
|
186 |
+
pos_embed = _get_pos_embedding(
|
187 |
+
all_vision_tokens.size(1) - self.num_cls_tokens,
|
188 |
+
pos_embed=self.pos_embed,
|
189 |
+
patches_layout=self.patches_layout,
|
190 |
+
input_shape=input_shape,
|
191 |
+
first_patch_idx=self.num_cls_tokens,
|
192 |
+
)
|
193 |
+
return pos_embed
|
194 |
+
|
195 |
+
|
196 |
+
class RGBDTPreprocessor(VerboseNNModule):
|
197 |
+
def __init__(
|
198 |
+
self,
|
199 |
+
rgbt_stem: PatchEmbedGeneric,
|
200 |
+
depth_stem: PatchEmbedGeneric,
|
201 |
+
img_size: List = (3, 224, 224),
|
202 |
+
num_cls_tokens: int = 1,
|
203 |
+
pos_embed_fn: Callable = None,
|
204 |
+
use_type_embed: bool = False,
|
205 |
+
init_param_style: str = "openclip",
|
206 |
+
) -> None:
|
207 |
+
super().__init__()
|
208 |
+
stem = rgbt_stem if rgbt_stem is not None else depth_stem
|
209 |
+
(
|
210 |
+
self.patches_layout,
|
211 |
+
self.num_patches,
|
212 |
+
self.embed_dim,
|
213 |
+
) = stem.get_patch_layout(img_size)
|
214 |
+
self.rgbt_stem = rgbt_stem
|
215 |
+
self.depth_stem = depth_stem
|
216 |
+
self.use_pos_embed = pos_embed_fn is not None
|
217 |
+
self.use_type_embed = use_type_embed
|
218 |
+
self.num_cls_tokens = num_cls_tokens
|
219 |
+
|
220 |
+
if self.use_pos_embed:
|
221 |
+
self.pos_embedding_helper = pos_embed_fn(
|
222 |
+
patches_layout=self.patches_layout,
|
223 |
+
num_cls_tokens=num_cls_tokens,
|
224 |
+
num_patches=self.num_patches,
|
225 |
+
embed_dim=self.embed_dim,
|
226 |
+
)
|
227 |
+
if self.num_cls_tokens > 0:
|
228 |
+
self.cls_token = nn.Parameter(
|
229 |
+
torch.zeros(1, self.num_cls_tokens, self.embed_dim)
|
230 |
+
)
|
231 |
+
if self.use_type_embed:
|
232 |
+
self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
|
233 |
+
|
234 |
+
self.init_parameters(init_param_style)
|
235 |
+
|
236 |
+
@torch.no_grad()
|
237 |
+
def init_parameters(self, init_param_style):
|
238 |
+
if init_param_style == "openclip":
|
239 |
+
# OpenCLIP style initialization
|
240 |
+
scale = self.embed_dim**-0.5
|
241 |
+
if self.use_pos_embed:
|
242 |
+
nn.init.normal_(self.pos_embedding_helper.pos_embed)
|
243 |
+
self.pos_embedding_helper.pos_embed *= scale
|
244 |
+
|
245 |
+
if self.num_cls_tokens > 0:
|
246 |
+
nn.init.normal_(self.cls_token)
|
247 |
+
self.cls_token *= scale
|
248 |
+
elif init_param_style == "vit":
|
249 |
+
self.cls_token.data.fill_(0)
|
250 |
+
else:
|
251 |
+
raise ValueError(f"Unknown init {init_param_style}")
|
252 |
+
|
253 |
+
if self.use_type_embed:
|
254 |
+
nn.init.normal_(self.type_embed)
|
255 |
+
|
256 |
+
def tokenize_input_and_cls_pos(self, input, stem, mask):
|
257 |
+
# tokens is of shape B x L x D
|
258 |
+
tokens = stem(input)
|
259 |
+
assert tokens.ndim == 3
|
260 |
+
assert tokens.shape[2] == self.embed_dim
|
261 |
+
B = tokens.shape[0]
|
262 |
+
if self.num_cls_tokens > 0:
|
263 |
+
class_tokens = self.cls_token.expand(
|
264 |
+
B, -1, -1
|
265 |
+
) # stole class_tokens impl from Phil Wang, thanks
|
266 |
+
tokens = torch.cat((class_tokens, tokens), dim=1)
|
267 |
+
if self.use_pos_embed:
|
268 |
+
pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens)
|
269 |
+
tokens = tokens + pos_embed
|
270 |
+
if self.use_type_embed:
|
271 |
+
tokens = tokens + self.type_embed.expand(B, -1, -1)
|
272 |
+
return tokens
|
273 |
+
|
274 |
+
def forward(self, vision=None, depth=None, patch_mask=None):
|
275 |
+
if patch_mask is not None:
|
276 |
+
raise NotImplementedError()
|
277 |
+
|
278 |
+
if vision is not None:
|
279 |
+
vision_tokens = self.tokenize_input_and_cls_pos(
|
280 |
+
vision, self.rgbt_stem, patch_mask
|
281 |
+
)
|
282 |
+
|
283 |
+
if depth is not None:
|
284 |
+
depth_tokens = self.tokenize_input_and_cls_pos(
|
285 |
+
depth, self.depth_stem, patch_mask
|
286 |
+
)
|
287 |
+
|
288 |
+
# aggregate tokens
|
289 |
+
if vision is not None and depth is not None:
|
290 |
+
final_tokens = vision_tokens + depth_tokens
|
291 |
+
else:
|
292 |
+
final_tokens = vision_tokens if vision is not None else depth_tokens
|
293 |
+
return_dict = {
|
294 |
+
"trunk": {
|
295 |
+
"tokens": final_tokens,
|
296 |
+
},
|
297 |
+
"head": {},
|
298 |
+
}
|
299 |
+
return return_dict
|
300 |
+
|
301 |
+
|
302 |
+
class AudioPreprocessor(RGBDTPreprocessor):
|
303 |
+
def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None:
|
304 |
+
super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs)
|
305 |
+
|
306 |
+
def forward(self, audio=None):
|
307 |
+
return super().forward(vision=audio)
|
308 |
+
|
309 |
+
|
310 |
+
class ThermalPreprocessor(RGBDTPreprocessor):
|
311 |
+
def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None:
|
312 |
+
super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs)
|
313 |
+
|
314 |
+
def forward(self, thermal=None):
|
315 |
+
return super().forward(vision=thermal)
|
316 |
+
|
317 |
+
|
318 |
+
def build_causal_attention_mask(context_length):
|
319 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
320 |
+
# pytorch uses additive attention mask; fill with -inf
|
321 |
+
mask = torch.empty(context_length, context_length, requires_grad=False)
|
322 |
+
mask.fill_(float("-inf"))
|
323 |
+
mask.triu_(1) # zero out the lower diagonal
|
324 |
+
return mask
|
325 |
+
|
326 |
+
|
327 |
+
class TextPreprocessor(VerboseNNModule):
|
328 |
+
def __init__(
|
329 |
+
self,
|
330 |
+
vocab_size: int,
|
331 |
+
context_length: int,
|
332 |
+
embed_dim: int,
|
333 |
+
causal_masking: bool,
|
334 |
+
supply_seq_len_to_head: bool = True,
|
335 |
+
num_cls_tokens: int = 0,
|
336 |
+
init_param_style: str = "openclip",
|
337 |
+
) -> None:
|
338 |
+
super().__init__()
|
339 |
+
self.vocab_size = vocab_size
|
340 |
+
self.context_length = context_length
|
341 |
+
self.token_embedding = nn.Embedding(vocab_size, embed_dim)
|
342 |
+
self.pos_embed = nn.Parameter(
|
343 |
+
torch.empty(1, self.context_length + num_cls_tokens, embed_dim)
|
344 |
+
)
|
345 |
+
self.causal_masking = causal_masking
|
346 |
+
if self.causal_masking:
|
347 |
+
mask = build_causal_attention_mask(self.context_length)
|
348 |
+
# register the mask as a buffer so it can be moved to the right device
|
349 |
+
self.register_buffer("mask", mask)
|
350 |
+
|
351 |
+
self.supply_seq_len_to_head = supply_seq_len_to_head
|
352 |
+
self.num_cls_tokens = num_cls_tokens
|
353 |
+
self.embed_dim = embed_dim
|
354 |
+
if num_cls_tokens > 0:
|
355 |
+
assert self.causal_masking is False, "Masking + CLS token isn't implemented"
|
356 |
+
self.cls_token = nn.Parameter(
|
357 |
+
torch.zeros(1, self.num_cls_tokens, embed_dim)
|
358 |
+
)
|
359 |
+
|
360 |
+
self.init_parameters(init_param_style)
|
361 |
+
|
362 |
+
@torch.no_grad()
|
363 |
+
def init_parameters(self, init_param_style="openclip"):
|
364 |
+
# OpenCLIP style initialization
|
365 |
+
nn.init.normal_(self.token_embedding.weight, std=0.02)
|
366 |
+
nn.init.normal_(self.pos_embed, std=0.01)
|
367 |
+
|
368 |
+
if init_param_style == "openclip":
|
369 |
+
# OpenCLIP style initialization
|
370 |
+
scale = self.embed_dim**-0.5
|
371 |
+
if self.num_cls_tokens > 0:
|
372 |
+
nn.init.normal_(self.cls_token)
|
373 |
+
self.cls_token *= scale
|
374 |
+
elif init_param_style == "vit":
|
375 |
+
self.cls_token.data.fill_(0)
|
376 |
+
else:
|
377 |
+
raise ValueError(f"Unknown init {init_param_style}")
|
378 |
+
|
379 |
+
def forward(self, text):
|
380 |
+
# text tokens are of shape B x L x D
|
381 |
+
text_tokens = self.token_embedding(text)
|
382 |
+
# concat CLS tokens if any
|
383 |
+
if self.num_cls_tokens > 0:
|
384 |
+
B = text_tokens.shape[0]
|
385 |
+
class_tokens = self.cls_token.expand(
|
386 |
+
B, -1, -1
|
387 |
+
) # stole class_tokens impl from Phil Wang, thanks
|
388 |
+
text_tokens = torch.cat((class_tokens, text_tokens), dim=1)
|
389 |
+
text_tokens = text_tokens + self.pos_embed
|
390 |
+
return_dict = {
|
391 |
+
"trunk": {
|
392 |
+
"tokens": text_tokens,
|
393 |
+
},
|
394 |
+
"head": {},
|
395 |
+
}
|
396 |
+
# Compute sequence length after adding CLS tokens
|
397 |
+
if self.supply_seq_len_to_head:
|
398 |
+
text_lengths = text.argmax(dim=-1)
|
399 |
+
return_dict["head"] = {
|
400 |
+
"seq_len": text_lengths,
|
401 |
+
}
|
402 |
+
if self.causal_masking:
|
403 |
+
return_dict["trunk"].update({"attn_mask": self.mask})
|
404 |
+
return return_dict
|
405 |
+
|
406 |
+
|
407 |
+
class Im2Video(nn.Module):
|
408 |
+
"""Convert an image into a trivial video."""
|
409 |
+
|
410 |
+
def __init__(self, time_dim=2):
|
411 |
+
super().__init__()
|
412 |
+
self.time_dim = time_dim
|
413 |
+
|
414 |
+
def forward(self, x):
|
415 |
+
if x.ndim == 4:
|
416 |
+
# B, C, H, W -> B, C, T, H, W
|
417 |
+
return x.unsqueeze(self.time_dim)
|
418 |
+
elif x.ndim == 5:
|
419 |
+
return x
|
420 |
+
else:
|
421 |
+
raise ValueError(f"Dimension incorrect {x.shape}")
|
422 |
+
|
423 |
+
|
424 |
+
class PadIm2Video(Im2Video):
|
425 |
+
def __init__(self, ntimes, pad_type, time_dim=2):
|
426 |
+
super().__init__(time_dim=time_dim)
|
427 |
+
assert ntimes > 0
|
428 |
+
assert pad_type in ["zero", "repeat"]
|
429 |
+
self.ntimes = ntimes
|
430 |
+
self.pad_type = pad_type
|
431 |
+
|
432 |
+
def forward(self, x):
|
433 |
+
x = super().forward(x)
|
434 |
+
if x.shape[self.time_dim] == 1:
|
435 |
+
if self.pad_type == "repeat":
|
436 |
+
new_shape = [1] * len(x.shape)
|
437 |
+
new_shape[self.time_dim] = self.ntimes
|
438 |
+
x = x.repeat(new_shape)
|
439 |
+
elif self.pad_type == "zero":
|
440 |
+
padarg = [0, 0] * len(x.shape)
|
441 |
+
padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim]
|
442 |
+
x = nn.functional.pad(x, padarg)
|
443 |
+
return x
|
444 |
+
|
445 |
+
|
446 |
+
# Modified from github.com/openai/CLIP
|
447 |
+
@lru_cache()
|
448 |
+
def bytes_to_unicode():
|
449 |
+
"""
|
450 |
+
Returns list of utf-8 byte and a corresponding list of unicode strings.
|
451 |
+
The reversible bpe codes work on unicode strings.
|
452 |
+
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
|
453 |
+
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
|
454 |
+
This is a signficant percentage of your normal, say, 32K bpe vocab.
|
455 |
+
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
456 |
+
And avoids mapping to whitespace/control characters the bpe code barfs on.
|
457 |
+
"""
|
458 |
+
bs = (
|
459 |
+
list(range(ord("!"), ord("~") + 1))
|
460 |
+
+ list(range(ord("¡"), ord("¬") + 1))
|
461 |
+
+ list(range(ord("®"), ord("ÿ") + 1))
|
462 |
+
)
|
463 |
+
cs = bs[:]
|
464 |
+
n = 0
|
465 |
+
for b in range(2**8):
|
466 |
+
if b not in bs:
|
467 |
+
bs.append(b)
|
468 |
+
cs.append(2**8 + n)
|
469 |
+
n += 1
|
470 |
+
cs = [chr(n) for n in cs]
|
471 |
+
return dict(zip(bs, cs))
|
472 |
+
|
473 |
+
|
474 |
+
def get_pairs(word):
|
475 |
+
"""Return set of symbol pairs in a word.
|
476 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
477 |
+
"""
|
478 |
+
pairs = set()
|
479 |
+
prev_char = word[0]
|
480 |
+
for char in word[1:]:
|
481 |
+
pairs.add((prev_char, char))
|
482 |
+
prev_char = char
|
483 |
+
return pairs
|
484 |
+
|
485 |
+
|
486 |
+
def basic_clean(text):
|
487 |
+
text = ftfy.fix_text(text)
|
488 |
+
text = html.unescape(html.unescape(text))
|
489 |
+
return text.strip()
|
490 |
+
|
491 |
+
|
492 |
+
def whitespace_clean(text):
|
493 |
+
text = re.sub(r"\s+", " ", text)
|
494 |
+
text = text.strip()
|
495 |
+
return text
|
496 |
+
|
497 |
+
|
498 |
+
class SimpleTokenizer(object):
|
499 |
+
def __init__(self, bpe_path: str, context_length=77):
|
500 |
+
self.byte_encoder = bytes_to_unicode()
|
501 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
502 |
+
|
503 |
+
with g_pathmgr.open(bpe_path, "rb") as fh:
|
504 |
+
bpe_bytes = io.BytesIO(fh.read())
|
505 |
+
merges = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
|
506 |
+
merges = merges[1 : 49152 - 256 - 2 + 1]
|
507 |
+
merges = [tuple(merge.split()) for merge in merges]
|
508 |
+
vocab = list(bytes_to_unicode().values())
|
509 |
+
vocab = vocab + [v + "</w>" for v in vocab]
|
510 |
+
for merge in merges:
|
511 |
+
vocab.append("".join(merge))
|
512 |
+
vocab.extend(["<|startoftext|>", "<|endoftext|>"])
|
513 |
+
self.encoder = dict(zip(vocab, range(len(vocab))))
|
514 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
515 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
516 |
+
self.cache = {
|
517 |
+
"<|startoftext|>": "<|startoftext|>",
|
518 |
+
"<|endoftext|>": "<|endoftext|>",
|
519 |
+
}
|
520 |
+
self.pat = re.compile(
|
521 |
+
r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
|
522 |
+
re.IGNORECASE,
|
523 |
+
)
|
524 |
+
self.context_length = context_length
|
525 |
+
|
526 |
+
def bpe(self, token):
|
527 |
+
if token in self.cache:
|
528 |
+
return self.cache[token]
|
529 |
+
word = tuple(token[:-1]) + (token[-1] + "</w>",)
|
530 |
+
pairs = get_pairs(word)
|
531 |
+
|
532 |
+
if not pairs:
|
533 |
+
return token + "</w>"
|
534 |
+
|
535 |
+
while True:
|
536 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
537 |
+
if bigram not in self.bpe_ranks:
|
538 |
+
break
|
539 |
+
first, second = bigram
|
540 |
+
new_word = []
|
541 |
+
i = 0
|
542 |
+
while i < len(word):
|
543 |
+
try:
|
544 |
+
j = word.index(first, i)
|
545 |
+
new_word.extend(word[i:j])
|
546 |
+
i = j
|
547 |
+
except:
|
548 |
+
new_word.extend(word[i:])
|
549 |
+
break
|
550 |
+
|
551 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
552 |
+
new_word.append(first + second)
|
553 |
+
i += 2
|
554 |
+
else:
|
555 |
+
new_word.append(word[i])
|
556 |
+
i += 1
|
557 |
+
new_word = tuple(new_word)
|
558 |
+
word = new_word
|
559 |
+
if len(word) == 1:
|
560 |
+
break
|
561 |
+
else:
|
562 |
+
pairs = get_pairs(word)
|
563 |
+
word = " ".join(word)
|
564 |
+
self.cache[token] = word
|
565 |
+
return word
|
566 |
+
|
567 |
+
def encode(self, text):
|
568 |
+
bpe_tokens = []
|
569 |
+
text = whitespace_clean(basic_clean(text)).lower()
|
570 |
+
for token in re.findall(self.pat, text):
|
571 |
+
token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
|
572 |
+
bpe_tokens.extend(
|
573 |
+
self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
|
574 |
+
)
|
575 |
+
return bpe_tokens
|
576 |
+
|
577 |
+
def decode(self, tokens):
|
578 |
+
text = "".join([self.decoder[token] for token in tokens])
|
579 |
+
text = (
|
580 |
+
bytearray([self.byte_decoder[c] for c in text])
|
581 |
+
.decode("utf-8", errors="replace")
|
582 |
+
.replace("</w>", " ")
|
583 |
+
)
|
584 |
+
return text
|
585 |
+
|
586 |
+
def __call__(self, texts, context_length=None):
|
587 |
+
if not context_length:
|
588 |
+
context_length = self.context_length
|
589 |
+
|
590 |
+
if isinstance(texts, str):
|
591 |
+
texts = [texts]
|
592 |
+
|
593 |
+
sot_token = self.encoder["<|startoftext|>"]
|
594 |
+
eot_token = self.encoder["<|endoftext|>"]
|
595 |
+
all_tokens = [[sot_token] + self.encode(text) + [eot_token] for text in texts]
|
596 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
|
597 |
+
|
598 |
+
for i, tokens in enumerate(all_tokens):
|
599 |
+
tokens = tokens[:context_length]
|
600 |
+
result[i, : len(tokens)] = torch.tensor(tokens)
|
601 |
+
|
602 |
+
if len(result) == 1:
|
603 |
+
return result[0]
|
604 |
+
return result
|
605 |
+
|
606 |
+
|
607 |
+
class IMUPreprocessor(VerboseNNModule):
|
608 |
+
def __init__(
|
609 |
+
self,
|
610 |
+
kernel_size: int,
|
611 |
+
imu_stem: PatchEmbedGeneric,
|
612 |
+
embed_dim: int,
|
613 |
+
img_size: List = (6, 2000),
|
614 |
+
num_cls_tokens: int = 1,
|
615 |
+
pos_embed_fn: Callable = None,
|
616 |
+
init_param_style: str = "openclip",
|
617 |
+
) -> None:
|
618 |
+
super().__init__()
|
619 |
+
stem = imu_stem
|
620 |
+
self.imu_stem = imu_stem
|
621 |
+
self.embed_dim = embed_dim
|
622 |
+
self.use_pos_embed = pos_embed_fn is not None
|
623 |
+
self.num_cls_tokens = num_cls_tokens
|
624 |
+
self.kernel_size = kernel_size
|
625 |
+
self.pos_embed = nn.Parameter(
|
626 |
+
torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim)
|
627 |
+
)
|
628 |
+
|
629 |
+
if self.num_cls_tokens > 0:
|
630 |
+
self.cls_token = nn.Parameter(
|
631 |
+
torch.zeros(1, self.num_cls_tokens, self.embed_dim)
|
632 |
+
)
|
633 |
+
|
634 |
+
self.init_parameters(init_param_style)
|
635 |
+
|
636 |
+
@torch.no_grad()
|
637 |
+
def init_parameters(self, init_param_style):
|
638 |
+
nn.init.normal_(self.pos_embed, std=0.01)
|
639 |
+
|
640 |
+
if init_param_style == "openclip":
|
641 |
+
# OpenCLIP style initialization
|
642 |
+
scale = self.embed_dim**-0.5
|
643 |
+
|
644 |
+
if self.num_cls_tokens > 0:
|
645 |
+
nn.init.normal_(self.cls_token)
|
646 |
+
self.cls_token *= scale
|
647 |
+
elif init_param_style == "vit":
|
648 |
+
self.cls_token.data.fill_(0)
|
649 |
+
else:
|
650 |
+
raise ValueError(f"Unknown init {init_param_style}")
|
651 |
+
|
652 |
+
def tokenize_input_and_cls_pos(self, input, stem):
|
653 |
+
# tokens is of shape B x L x D
|
654 |
+
tokens = stem.norm_layer(stem.proj(input))
|
655 |
+
assert tokens.ndim == 3
|
656 |
+
assert tokens.shape[2] == self.embed_dim
|
657 |
+
B = tokens.shape[0]
|
658 |
+
if self.num_cls_tokens > 0:
|
659 |
+
class_tokens = self.cls_token.expand(
|
660 |
+
B, -1, -1
|
661 |
+
) # stole class_tokens impl from Phil Wang, thanks
|
662 |
+
tokens = torch.cat((class_tokens, tokens), dim=1)
|
663 |
+
if self.use_pos_embed:
|
664 |
+
tokens = tokens + self.pos_embed
|
665 |
+
return tokens
|
666 |
+
|
667 |
+
def forward(self, imu):
|
668 |
+
# Patchify
|
669 |
+
imu = imu.unfold(
|
670 |
+
-1,
|
671 |
+
self.kernel_size,
|
672 |
+
self.kernel_size,
|
673 |
+
).permute(0, 2, 1, 3)
|
674 |
+
imu = imu.reshape(imu.size(0), imu.size(1), -1)
|
675 |
+
|
676 |
+
imu_tokens = self.tokenize_input_and_cls_pos(
|
677 |
+
imu,
|
678 |
+
self.imu_stem,
|
679 |
+
)
|
680 |
+
|
681 |
+
return_dict = {
|
682 |
+
"trunk": {
|
683 |
+
"tokens": imu_tokens,
|
684 |
+
},
|
685 |
+
"head": {},
|
686 |
+
}
|
687 |
+
return return_dict
|
model/ImageBind/models/transformer.py
ADDED
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
|
3 |
+
# All rights reserved.
|
4 |
+
|
5 |
+
# This source code is licensed under the license found in the
|
6 |
+
# LICENSE file in the root directory of this source tree.
|
7 |
+
|
8 |
+
# Code modified from
|
9 |
+
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ;
|
10 |
+
# https://github.com/facebookresearch/deit/blob/main/models.py
|
11 |
+
# and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py
|
12 |
+
|
13 |
+
|
14 |
+
import copy
|
15 |
+
import fnmatch
|
16 |
+
import logging
|
17 |
+
from functools import partial
|
18 |
+
from typing import Callable, List
|
19 |
+
|
20 |
+
import torch
|
21 |
+
import torch.nn as nn
|
22 |
+
import torch.utils.checkpoint as checkpoint
|
23 |
+
|
24 |
+
from timm.models.layers import DropPath, trunc_normal_
|
25 |
+
|
26 |
+
|
27 |
+
class Attention(nn.Module):
|
28 |
+
def __init__(
|
29 |
+
self,
|
30 |
+
dim,
|
31 |
+
num_heads=8,
|
32 |
+
qkv_bias=False,
|
33 |
+
qk_scale=None,
|
34 |
+
attn_drop=0.0,
|
35 |
+
proj_drop=0.0,
|
36 |
+
):
|
37 |
+
super().__init__()
|
38 |
+
self.num_heads = num_heads
|
39 |
+
head_dim = dim // num_heads
|
40 |
+
# NOTE scale factor was wrong in my original version,
|
41 |
+
# can set manually to be compat with prev weights
|
42 |
+
self.scale = qk_scale or head_dim**-0.5
|
43 |
+
|
44 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
45 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
46 |
+
self.proj = nn.Linear(dim, dim)
|
47 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
48 |
+
|
49 |
+
def forward(self, x):
|
50 |
+
B, N, C = x.shape
|
51 |
+
qkv = (
|
52 |
+
self.qkv(x)
|
53 |
+
.reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
54 |
+
.permute(2, 0, 3, 1, 4)
|
55 |
+
)
|
56 |
+
q, k, v = (
|
57 |
+
qkv[0],
|
58 |
+
qkv[1],
|
59 |
+
qkv[2],
|
60 |
+
) # make torchscript happy (cannot use tensor as tuple)
|
61 |
+
|
62 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
63 |
+
attn = attn.softmax(dim=-1)
|
64 |
+
attn = self.attn_drop(attn)
|
65 |
+
|
66 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
67 |
+
x = self.proj(x)
|
68 |
+
x = self.proj_drop(x)
|
69 |
+
return x
|
70 |
+
|
71 |
+
|
72 |
+
class Mlp(nn.Module):
|
73 |
+
def __init__(
|
74 |
+
self,
|
75 |
+
in_features,
|
76 |
+
hidden_features=None,
|
77 |
+
out_features=None,
|
78 |
+
act_layer=nn.GELU,
|
79 |
+
drop=0.0,
|
80 |
+
):
|
81 |
+
super().__init__()
|
82 |
+
out_features = out_features or in_features
|
83 |
+
hidden_features = hidden_features or in_features
|
84 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
85 |
+
self.act = act_layer()
|
86 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
87 |
+
self.drop = nn.Dropout(drop)
|
88 |
+
|
89 |
+
def forward(self, x):
|
90 |
+
x = self.fc1(x)
|
91 |
+
x = self.act(x)
|
92 |
+
x = self.drop(x)
|
93 |
+
x = self.fc2(x)
|
94 |
+
x = self.drop(x)
|
95 |
+
return x
|
96 |
+
|
97 |
+
|
98 |
+
class MultiheadAttention(nn.MultiheadAttention):
|
99 |
+
def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
|
100 |
+
return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
|
101 |
+
|
102 |
+
|
103 |
+
class ViTAttention(Attention):
|
104 |
+
def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
|
105 |
+
assert attn_mask is None
|
106 |
+
return super().forward(x)
|
107 |
+
|
108 |
+
|
109 |
+
class BlockWithMasking(nn.Module):
|
110 |
+
def __init__(
|
111 |
+
self,
|
112 |
+
dim: int,
|
113 |
+
attn_target: Callable,
|
114 |
+
mlp_ratio: int = 4,
|
115 |
+
act_layer: Callable = nn.GELU,
|
116 |
+
norm_layer: Callable = nn.LayerNorm,
|
117 |
+
ffn_dropout_rate: float = 0.0,
|
118 |
+
drop_path: float = 0.0,
|
119 |
+
layer_scale_type: str = None,
|
120 |
+
layer_scale_init_value: float = 1e-4,
|
121 |
+
):
|
122 |
+
super().__init__()
|
123 |
+
|
124 |
+
assert not isinstance(
|
125 |
+
attn_target, nn.Module
|
126 |
+
), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!"
|
127 |
+
self.attn = attn_target()
|
128 |
+
if drop_path > 0.0:
|
129 |
+
self.drop_path = DropPath(drop_path)
|
130 |
+
else:
|
131 |
+
self.drop_path = nn.Identity()
|
132 |
+
self.norm_1 = norm_layer(dim)
|
133 |
+
mlp_hidden_dim = int(mlp_ratio * dim)
|
134 |
+
self.mlp = Mlp(
|
135 |
+
in_features=dim,
|
136 |
+
hidden_features=mlp_hidden_dim,
|
137 |
+
act_layer=act_layer,
|
138 |
+
drop=ffn_dropout_rate,
|
139 |
+
)
|
140 |
+
self.norm_2 = norm_layer(dim)
|
141 |
+
self.layer_scale_type = layer_scale_type
|
142 |
+
if self.layer_scale_type is not None:
|
143 |
+
assert self.layer_scale_type in [
|
144 |
+
"per_channel",
|
145 |
+
"scalar",
|
146 |
+
], f"Found Layer scale type {self.layer_scale_type}"
|
147 |
+
if self.layer_scale_type == "per_channel":
|
148 |
+
# one gamma value per channel
|
149 |
+
gamma_shape = [1, 1, dim]
|
150 |
+
elif self.layer_scale_type == "scalar":
|
151 |
+
# single gamma value for all channels
|
152 |
+
gamma_shape = [1, 1, 1]
|
153 |
+
# two gammas: for each part of the fwd in the encoder
|
154 |
+
self.layer_scale_gamma1 = nn.Parameter(
|
155 |
+
torch.ones(size=gamma_shape) * layer_scale_init_value,
|
156 |
+
requires_grad=True,
|
157 |
+
)
|
158 |
+
self.layer_scale_gamma2 = nn.Parameter(
|
159 |
+
torch.ones(size=gamma_shape) * layer_scale_init_value,
|
160 |
+
requires_grad=True,
|
161 |
+
)
|
162 |
+
|
163 |
+
def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
|
164 |
+
if self.layer_scale_type is None:
|
165 |
+
x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))
|
166 |
+
x = x + self.drop_path(self.mlp(self.norm_2(x)))
|
167 |
+
else:
|
168 |
+
x = (
|
169 |
+
x
|
170 |
+
+ self.drop_path(self.attn(self.norm_1(x), attn_mask))
|
171 |
+
* self.layer_scale_gamma1
|
172 |
+
)
|
173 |
+
x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2
|
174 |
+
return x
|
175 |
+
|
176 |
+
|
177 |
+
_LAYER_NORM = partial(nn.LayerNorm, eps=1e-6)
|
178 |
+
|
179 |
+
|
180 |
+
class SimpleTransformer(nn.Module):
|
181 |
+
def __init__(
|
182 |
+
self,
|
183 |
+
attn_target: Callable,
|
184 |
+
embed_dim: int,
|
185 |
+
num_blocks: int,
|
186 |
+
block: Callable = BlockWithMasking,
|
187 |
+
pre_transformer_layer: Callable = None,
|
188 |
+
post_transformer_layer: Callable = None,
|
189 |
+
drop_path_rate: float = 0.0,
|
190 |
+
drop_path_type: str = "progressive",
|
191 |
+
norm_layer: Callable = _LAYER_NORM,
|
192 |
+
mlp_ratio: int = 4,
|
193 |
+
ffn_dropout_rate: float = 0.0,
|
194 |
+
layer_scale_type: str = None, # from cait; possible values are None, "per_channel", "scalar"
|
195 |
+
layer_scale_init_value: float = 1e-4, # from cait; float
|
196 |
+
weight_init_style: str = "jax", # possible values jax or pytorch
|
197 |
+
):
|
198 |
+
"""
|
199 |
+
Simple Transformer with the following features
|
200 |
+
1. Supports masked attention
|
201 |
+
2. Supports DropPath
|
202 |
+
3. Supports LayerScale
|
203 |
+
4. Supports Dropout in Attention and FFN
|
204 |
+
5. Makes few assumptions about the input except that it is a Tensor
|
205 |
+
"""
|
206 |
+
super().__init__()
|
207 |
+
self.pre_transformer_layer = pre_transformer_layer
|
208 |
+
if drop_path_type == "progressive":
|
209 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)]
|
210 |
+
elif drop_path_type == "uniform":
|
211 |
+
dpr = [drop_path_rate for i in range(num_blocks)]
|
212 |
+
else:
|
213 |
+
raise ValueError(f"Unknown drop_path_type: {drop_path_type}")
|
214 |
+
|
215 |
+
self.blocks = nn.Sequential(
|
216 |
+
*[
|
217 |
+
block(
|
218 |
+
dim=embed_dim,
|
219 |
+
attn_target=attn_target,
|
220 |
+
mlp_ratio=mlp_ratio,
|
221 |
+
ffn_dropout_rate=ffn_dropout_rate,
|
222 |
+
drop_path=dpr[i],
|
223 |
+
norm_layer=norm_layer,
|
224 |
+
layer_scale_type=layer_scale_type,
|
225 |
+
layer_scale_init_value=layer_scale_init_value,
|
226 |
+
)
|
227 |
+
for i in range(num_blocks)
|
228 |
+
]
|
229 |
+
)
|
230 |
+
self.post_transformer_layer = post_transformer_layer
|
231 |
+
self.weight_init_style = weight_init_style
|
232 |
+
self.apply(self._init_weights)
|
233 |
+
|
234 |
+
def _init_weights(self, m):
|
235 |
+
if isinstance(m, nn.Linear):
|
236 |
+
if self.weight_init_style == "jax":
|
237 |
+
# Based on MAE and official Jax ViT implementation
|
238 |
+
torch.nn.init.xavier_uniform_(m.weight)
|
239 |
+
elif self.weight_init_style == "pytorch":
|
240 |
+
# PyTorch ViT uses trunc_normal_
|
241 |
+
trunc_normal_(m.weight, std=0.02)
|
242 |
+
|
243 |
+
if m.bias is not None:
|
244 |
+
nn.init.constant_(m.bias, 0)
|
245 |
+
elif isinstance(m, (nn.LayerNorm)):
|
246 |
+
nn.init.constant_(m.bias, 0)
|
247 |
+
nn.init.constant_(m.weight, 1.0)
|
248 |
+
|
249 |
+
def forward(
|
250 |
+
self,
|
251 |
+
tokens: torch.Tensor,
|
252 |
+
attn_mask: torch.Tensor = None,
|
253 |
+
use_checkpoint: bool = False,
|
254 |
+
checkpoint_every_n: int = 1,
|
255 |
+
checkpoint_blk_ids: List[int] = None,
|
256 |
+
):
|
257 |
+
"""
|
258 |
+
Inputs
|
259 |
+
- tokens: data of shape N x L x D (or L x N x D depending on the attention implementation)
|
260 |
+
- attn: mask of shape L x L
|
261 |
+
|
262 |
+
Output
|
263 |
+
- x: data of shape N x L x D (or L x N x D depending on the attention implementation)
|
264 |
+
"""
|
265 |
+
if self.pre_transformer_layer:
|
266 |
+
tokens = self.pre_transformer_layer(tokens)
|
267 |
+
if use_checkpoint and checkpoint_blk_ids is None:
|
268 |
+
checkpoint_blk_ids = [
|
269 |
+
blk_id
|
270 |
+
for blk_id in range(len(self.blocks))
|
271 |
+
if blk_id % checkpoint_every_n == 0
|
272 |
+
]
|
273 |
+
if checkpoint_blk_ids:
|
274 |
+
checkpoint_blk_ids = set(checkpoint_blk_ids)
|
275 |
+
for blk_id, blk in enumerate(self.blocks):
|
276 |
+
if use_checkpoint and blk_id in checkpoint_blk_ids:
|
277 |
+
tokens = checkpoint.checkpoint(
|
278 |
+
blk, tokens, attn_mask, use_reentrant=False
|
279 |
+
)
|
280 |
+
else:
|
281 |
+
tokens = blk(tokens, attn_mask=attn_mask)
|
282 |
+
if self.post_transformer_layer:
|
283 |
+
tokens = self.post_transformer_layer(tokens)
|
284 |
+
return tokens
|
model/ImageBind/requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--extra-index-url https://download.pytorch.org/whl/cu113
|
2 |
+
torchvision==0.14.0
|
3 |
+
torchaudio==0.13.0
|
4 |
+
pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d
|
5 |
+
timm==0.6.7
|
6 |
+
ftfy
|
7 |
+
regex
|
8 |
+
einops
|
9 |
+
fvcore
|
10 |
+
decord==0.6.0
|
model/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .agent import DeepSpeedAgent
|
2 |
+
from .openllama import OpenLLAMAPEFTModel
|
3 |
+
|
4 |
+
def load_model(args):
|
5 |
+
agent_name = args['models'][args['model']]['agent_name']
|
6 |
+
model_name = args['models'][args['model']]['model_name']
|
7 |
+
model = globals()[model_name](**args)
|
8 |
+
agent = globals()[agent_name](model, args)
|
9 |
+
return agent
|
model/agent.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from header import *
|
2 |
+
|
3 |
+
class DeepSpeedAgent:
|
4 |
+
|
5 |
+
def __init__(self, model, args):
|
6 |
+
super(DeepSpeedAgent, self).__init__()
|
7 |
+
self.args = args
|
8 |
+
self.model = model
|
9 |
+
if args['stage'] == 2:
|
10 |
+
self.load_stage_1_parameters(args["delta_ckpt_path"])
|
11 |
+
print(f'[!] load stage 1 checkpoint from {args["delta_ckpt_path"]}')
|
12 |
+
|
13 |
+
# load config parameters of deepspeed
|
14 |
+
ds_params = json.load(open(self.args['ds_config_path']))
|
15 |
+
ds_params['scheduler']['params']['total_num_steps'] = self.args['total_steps']
|
16 |
+
ds_params['scheduler']['params']['warmup_num_steps'] = max(10, int(self.args['total_steps'] * self.args['warmup_rate']))
|
17 |
+
self.ds_engine, self.optimizer, _ , _ = deepspeed.initialize(
|
18 |
+
model=self.model,
|
19 |
+
model_parameters=self.model.parameters(),
|
20 |
+
config_params=ds_params,
|
21 |
+
dist_init_required=True,
|
22 |
+
args=types.SimpleNamespace(**args)
|
23 |
+
)
|
24 |
+
|
25 |
+
@torch.no_grad()
|
26 |
+
def predict(self, batch):
|
27 |
+
self.model.eval()
|
28 |
+
string = self.model.generate_one_sample(batch)
|
29 |
+
return string
|
30 |
+
|
31 |
+
def train_model(self, batch, current_step=0, pbar=None):
|
32 |
+
self.ds_engine.module.train()
|
33 |
+
loss, mle_acc = self.ds_engine(batch)
|
34 |
+
|
35 |
+
self.ds_engine.backward(loss)
|
36 |
+
self.ds_engine.step()
|
37 |
+
pbar.set_description(f'[!] loss: {round(loss.item(), 4)}; token_acc: {round(mle_acc*100, 2)}')
|
38 |
+
pbar.update(1)
|
39 |
+
if self.args['local_rank'] == 0 and self.args['log_path'] and current_step % self.args['logging_step'] == 0:
|
40 |
+
elapsed = pbar.format_dict['elapsed']
|
41 |
+
rate = pbar.format_dict['rate']
|
42 |
+
remaining = (pbar.total - pbar.n) / rate if rate and pbar.total else 0
|
43 |
+
remaining = str(datetime.timedelta(seconds=remaining))
|
44 |
+
logging.info(f'[!] progress: {round(pbar.n/pbar.total, 5)}; remaining time: {remaining}; loss: {round(loss.item(), 4)}; token_acc: {round(mle_acc*100, 2)}')
|
45 |
+
|
46 |
+
mle_acc *= 100
|
47 |
+
return mle_acc
|
48 |
+
|
49 |
+
def save_model(self, path, current_step):
|
50 |
+
# only save trainable model parameters
|
51 |
+
param_grad_dic = {
|
52 |
+
k: v.requires_grad for (k, v) in self.ds_engine.module.named_parameters()
|
53 |
+
}
|
54 |
+
state_dict = self.ds_engine.module.state_dict()
|
55 |
+
checkpoint = OrderedDict()
|
56 |
+
for k, v in self.ds_engine.module.named_parameters():
|
57 |
+
if v.requires_grad:
|
58 |
+
checkpoint[k] = v
|
59 |
+
torch.save(checkpoint, f'{path}/pytorch_model.pt')
|
60 |
+
# save tokenizer
|
61 |
+
self.model.llama_tokenizer.save_pretrained(path)
|
62 |
+
# save configuration
|
63 |
+
self.model.llama_model.config.save_pretrained(path)
|
64 |
+
print(f'[!] save model into {path}')
|
65 |
+
|
66 |
+
def load_stage_1_parameters(self, path):
|
67 |
+
delta_ckpt = torch.load(path, map_location=torch.device('cpu'))
|
68 |
+
self.model.load_state_dict(delta_ckpt, strict=False)
|
model/modeling_llama.py
ADDED
@@ -0,0 +1,755 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This script is based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
|
2 |
+
|
3 |
+
""" PyTorch LLaMA model."""
|
4 |
+
import math
|
5 |
+
from typing import List, Optional, Tuple, Union
|
6 |
+
|
7 |
+
import torch
|
8 |
+
import torch.utils.checkpoint
|
9 |
+
from torch import nn
|
10 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
11 |
+
|
12 |
+
from transformers.activations import ACT2FN
|
13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
14 |
+
from transformers.modeling_utils import PreTrainedModel
|
15 |
+
from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
16 |
+
from transformers.models.llama.configuration_llama import LlamaConfig
|
17 |
+
|
18 |
+
|
19 |
+
logger = logging.get_logger(__name__)
|
20 |
+
|
21 |
+
_CONFIG_FOR_DOC = "LlamaConfig"
|
22 |
+
|
23 |
+
|
24 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
25 |
+
def _make_causal_mask(
|
26 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
27 |
+
):
|
28 |
+
"""
|
29 |
+
Make causal mask used for bi-directional self-attention.
|
30 |
+
"""
|
31 |
+
bsz, tgt_len = input_ids_shape
|
32 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
33 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
34 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
35 |
+
mask = mask.to(dtype)
|
36 |
+
|
37 |
+
if past_key_values_length > 0:
|
38 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
39 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
40 |
+
|
41 |
+
|
42 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
43 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
44 |
+
"""
|
45 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
46 |
+
"""
|
47 |
+
bsz, src_len = mask.size()
|
48 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
49 |
+
|
50 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
51 |
+
|
52 |
+
inverted_mask = 1.0 - expanded_mask
|
53 |
+
|
54 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
55 |
+
|
56 |
+
|
57 |
+
class LlamaRMSNorm(nn.Module):
|
58 |
+
def __init__(self, hidden_size, eps=1e-6):
|
59 |
+
"""
|
60 |
+
LlamaRMSNorm is equivalent to T5LayerNorm
|
61 |
+
"""
|
62 |
+
super().__init__()
|
63 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
64 |
+
self.variance_epsilon = eps
|
65 |
+
|
66 |
+
def forward(self, hidden_states):
|
67 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
68 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
69 |
+
|
70 |
+
# convert into half-precision if necessary
|
71 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
72 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
73 |
+
|
74 |
+
return self.weight * hidden_states
|
75 |
+
|
76 |
+
|
77 |
+
class LlamaRotaryEmbedding(torch.nn.Module):
|
78 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
79 |
+
super().__init__()
|
80 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
81 |
+
self.register_buffer("inv_freq", inv_freq)
|
82 |
+
|
83 |
+
# Build here to make `torch.jit.trace` work.
|
84 |
+
self.max_seq_len_cached = max_position_embeddings
|
85 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
86 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
87 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
88 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
89 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
|
90 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
|
91 |
+
|
92 |
+
def forward(self, x, seq_len=None):
|
93 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
94 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
95 |
+
if seq_len > self.max_seq_len_cached:
|
96 |
+
self.max_seq_len_cached = seq_len
|
97 |
+
t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
|
98 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
99 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
100 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
101 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
|
102 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
|
103 |
+
return (
|
104 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
105 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
106 |
+
)
|
107 |
+
|
108 |
+
|
109 |
+
def rotate_half(x):
|
110 |
+
"""Rotates half the hidden dims of the input."""
|
111 |
+
x1 = x[..., : x.shape[-1] // 2]
|
112 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
113 |
+
return torch.cat((-x2, x1), dim=-1)
|
114 |
+
|
115 |
+
|
116 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
117 |
+
gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
|
118 |
+
gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
|
119 |
+
cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
|
120 |
+
sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
|
121 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
122 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
123 |
+
return q_embed, k_embed
|
124 |
+
|
125 |
+
|
126 |
+
class LlamaMLP(nn.Module):
|
127 |
+
def __init__(
|
128 |
+
self,
|
129 |
+
hidden_size: int,
|
130 |
+
intermediate_size: int,
|
131 |
+
hidden_act: str,
|
132 |
+
):
|
133 |
+
super().__init__()
|
134 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
135 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
136 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
137 |
+
self.act_fn = ACT2FN[hidden_act]
|
138 |
+
|
139 |
+
def forward(self, x):
|
140 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
141 |
+
|
142 |
+
|
143 |
+
class LlamaAttention(nn.Module):
|
144 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
145 |
+
|
146 |
+
def __init__(self, config: LlamaConfig):
|
147 |
+
super().__init__()
|
148 |
+
self.config = config
|
149 |
+
self.hidden_size = config.hidden_size
|
150 |
+
self.num_heads = config.num_attention_heads
|
151 |
+
self.head_dim = self.hidden_size // self.num_heads
|
152 |
+
self.max_position_embeddings = config.max_position_embeddings
|
153 |
+
|
154 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
155 |
+
raise ValueError(
|
156 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
157 |
+
f" and `num_heads`: {self.num_heads})."
|
158 |
+
)
|
159 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
160 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
161 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
162 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
163 |
+
self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
164 |
+
|
165 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
166 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
167 |
+
|
168 |
+
def forward(
|
169 |
+
self,
|
170 |
+
hidden_states: torch.Tensor,
|
171 |
+
attention_mask: Optional[torch.Tensor] = None,
|
172 |
+
position_ids: Optional[torch.LongTensor] = None,
|
173 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
174 |
+
output_attentions: bool = False,
|
175 |
+
use_cache: bool = False,
|
176 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
177 |
+
bsz, q_len, _ = hidden_states.size()
|
178 |
+
|
179 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
180 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
181 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
182 |
+
|
183 |
+
kv_seq_len = key_states.shape[-2]
|
184 |
+
if past_key_value is not None:
|
185 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
186 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
187 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
188 |
+
# [bsz, nh, t, hd]
|
189 |
+
|
190 |
+
if past_key_value is not None:
|
191 |
+
# reuse k, v, self_attention
|
192 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
193 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
194 |
+
|
195 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
196 |
+
|
197 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
198 |
+
|
199 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
200 |
+
raise ValueError(
|
201 |
+
f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
|
202 |
+
f" {attn_weights.size()}"
|
203 |
+
)
|
204 |
+
|
205 |
+
if attention_mask is not None:
|
206 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
207 |
+
raise ValueError(
|
208 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
209 |
+
)
|
210 |
+
attn_weights = attn_weights + attention_mask
|
211 |
+
attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
|
212 |
+
|
213 |
+
# upcast attention to fp32
|
214 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
215 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
216 |
+
|
217 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
218 |
+
raise ValueError(
|
219 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
220 |
+
f" {attn_output.size()}"
|
221 |
+
)
|
222 |
+
|
223 |
+
attn_output = attn_output.transpose(1, 2)
|
224 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
225 |
+
|
226 |
+
attn_output = self.o_proj(attn_output)
|
227 |
+
|
228 |
+
if not output_attentions:
|
229 |
+
attn_weights = None
|
230 |
+
|
231 |
+
return attn_output, attn_weights, past_key_value
|
232 |
+
|
233 |
+
|
234 |
+
class LlamaDecoderLayer(nn.Module):
|
235 |
+
def __init__(self, config: LlamaConfig):
|
236 |
+
super().__init__()
|
237 |
+
self.hidden_size = config.hidden_size
|
238 |
+
self.self_attn = LlamaAttention(config=config)
|
239 |
+
self.mlp = LlamaMLP(
|
240 |
+
hidden_size=self.hidden_size,
|
241 |
+
intermediate_size=config.intermediate_size,
|
242 |
+
hidden_act=config.hidden_act,
|
243 |
+
)
|
244 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
245 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
246 |
+
|
247 |
+
def forward(
|
248 |
+
self,
|
249 |
+
hidden_states: torch.Tensor,
|
250 |
+
attention_mask: Optional[torch.Tensor] = None,
|
251 |
+
position_ids: Optional[torch.LongTensor] = None,
|
252 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
253 |
+
output_attentions: Optional[bool] = False,
|
254 |
+
use_cache: Optional[bool] = False,
|
255 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
256 |
+
"""
|
257 |
+
Args:
|
258 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
259 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
260 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
261 |
+
output_attentions (`bool`, *optional*):
|
262 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
263 |
+
returned tensors for more detail.
|
264 |
+
use_cache (`bool`, *optional*):
|
265 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
266 |
+
(see `past_key_values`).
|
267 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
268 |
+
"""
|
269 |
+
|
270 |
+
residual = hidden_states
|
271 |
+
|
272 |
+
hidden_states = self.input_layernorm(hidden_states)
|
273 |
+
|
274 |
+
# Self Attention
|
275 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
276 |
+
hidden_states=hidden_states,
|
277 |
+
attention_mask=attention_mask,
|
278 |
+
position_ids=position_ids,
|
279 |
+
past_key_value=past_key_value,
|
280 |
+
output_attentions=output_attentions,
|
281 |
+
use_cache=use_cache,
|
282 |
+
)
|
283 |
+
hidden_states = residual + hidden_states
|
284 |
+
|
285 |
+
# Fully Connected
|
286 |
+
residual = hidden_states
|
287 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
288 |
+
hidden_states = self.mlp(hidden_states)
|
289 |
+
hidden_states = residual + hidden_states
|
290 |
+
|
291 |
+
outputs = (hidden_states,)
|
292 |
+
|
293 |
+
if output_attentions:
|
294 |
+
outputs += (self_attn_weights,)
|
295 |
+
|
296 |
+
if use_cache:
|
297 |
+
outputs += (present_key_value,)
|
298 |
+
|
299 |
+
return outputs
|
300 |
+
|
301 |
+
|
302 |
+
LLAMA_START_DOCSTRING = r"""
|
303 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
304 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
305 |
+
etc.)
|
306 |
+
|
307 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
308 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
309 |
+
and behavior.
|
310 |
+
|
311 |
+
Parameters:
|
312 |
+
config ([`LlamaConfig`]):
|
313 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
314 |
+
load the weights associated with the model, only the configuration. Check out the
|
315 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
316 |
+
"""
|
317 |
+
|
318 |
+
|
319 |
+
@add_start_docstrings(
|
320 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
321 |
+
LLAMA_START_DOCSTRING,
|
322 |
+
)
|
323 |
+
class LlamaPreTrainedModel(PreTrainedModel):
|
324 |
+
config_class = LlamaConfig
|
325 |
+
base_model_prefix = "model"
|
326 |
+
supports_gradient_checkpointing = True
|
327 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
328 |
+
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
329 |
+
|
330 |
+
def _init_weights(self, module):
|
331 |
+
std = self.config.initializer_range
|
332 |
+
if isinstance(module, nn.Linear):
|
333 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
334 |
+
if module.bias is not None:
|
335 |
+
module.bias.data.zero_()
|
336 |
+
elif isinstance(module, nn.Embedding):
|
337 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
338 |
+
if module.padding_idx is not None:
|
339 |
+
module.weight.data[module.padding_idx].zero_()
|
340 |
+
|
341 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
342 |
+
if isinstance(module, LlamaModel):
|
343 |
+
module.gradient_checkpointing = value
|
344 |
+
|
345 |
+
|
346 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
347 |
+
Args:
|
348 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
349 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
350 |
+
it.
|
351 |
+
|
352 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
353 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
354 |
+
|
355 |
+
[What are input IDs?](../glossary#input-ids)
|
356 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
357 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
358 |
+
|
359 |
+
- 1 for tokens that are **not masked**,
|
360 |
+
- 0 for tokens that are **masked**.
|
361 |
+
|
362 |
+
[What are attention masks?](../glossary#attention-mask)
|
363 |
+
|
364 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
365 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
366 |
+
|
367 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
368 |
+
`past_key_values`).
|
369 |
+
|
370 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
371 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
372 |
+
information on the default strategy.
|
373 |
+
|
374 |
+
- 1 indicates the head is **not masked**,
|
375 |
+
- 0 indicates the head is **masked**.
|
376 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
377 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
378 |
+
config.n_positions - 1]`.
|
379 |
+
|
380 |
+
[What are position IDs?](../glossary#position-ids)
|
381 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
382 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
383 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
384 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
385 |
+
|
386 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
387 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
388 |
+
|
389 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
390 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
391 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
392 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
393 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
394 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
395 |
+
model's internal embedding lookup matrix.
|
396 |
+
use_cache (`bool`, *optional*):
|
397 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
398 |
+
`past_key_values`).
|
399 |
+
output_attentions (`bool`, *optional*):
|
400 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
401 |
+
tensors for more detail.
|
402 |
+
output_hidden_states (`bool`, *optional*):
|
403 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
404 |
+
more detail.
|
405 |
+
return_dict (`bool`, *optional*):
|
406 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
407 |
+
"""
|
408 |
+
|
409 |
+
|
410 |
+
@add_start_docstrings(
|
411 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
412 |
+
LLAMA_START_DOCSTRING,
|
413 |
+
)
|
414 |
+
class LlamaModel(LlamaPreTrainedModel):
|
415 |
+
"""
|
416 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
417 |
+
|
418 |
+
Args:
|
419 |
+
config: LlamaConfig
|
420 |
+
"""
|
421 |
+
|
422 |
+
def __init__(self, config: LlamaConfig):
|
423 |
+
super().__init__(config)
|
424 |
+
self.padding_idx = config.pad_token_id
|
425 |
+
self.vocab_size = config.vocab_size
|
426 |
+
|
427 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
428 |
+
self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
429 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
430 |
+
|
431 |
+
self.gradient_checkpointing = False
|
432 |
+
# Initialize weights and apply final processing
|
433 |
+
self.post_init()
|
434 |
+
|
435 |
+
def get_input_embeddings(self):
|
436 |
+
return self.embed_tokens
|
437 |
+
|
438 |
+
def set_input_embeddings(self, value):
|
439 |
+
self.embed_tokens = value
|
440 |
+
|
441 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
442 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
443 |
+
# create causal mask
|
444 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
445 |
+
combined_attention_mask = None
|
446 |
+
if input_shape[-1] > 1:
|
447 |
+
combined_attention_mask = _make_causal_mask(
|
448 |
+
input_shape,
|
449 |
+
inputs_embeds.dtype,
|
450 |
+
device=inputs_embeds.device,
|
451 |
+
past_key_values_length=past_key_values_length,
|
452 |
+
)
|
453 |
+
|
454 |
+
if attention_mask is not None:
|
455 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
456 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
457 |
+
inputs_embeds.device
|
458 |
+
)
|
459 |
+
combined_attention_mask = (
|
460 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
461 |
+
)
|
462 |
+
|
463 |
+
return combined_attention_mask
|
464 |
+
|
465 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
466 |
+
def forward(
|
467 |
+
self,
|
468 |
+
input_ids: torch.LongTensor = None,
|
469 |
+
attention_mask: Optional[torch.Tensor] = None,
|
470 |
+
position_ids: Optional[torch.LongTensor] = None,
|
471 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
472 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
473 |
+
query_embeds: Optional[torch.FloatTensor] = None,
|
474 |
+
use_cache: Optional[bool] = None,
|
475 |
+
output_attentions: Optional[bool] = None,
|
476 |
+
output_hidden_states: Optional[bool] = None,
|
477 |
+
return_dict: Optional[bool] = None,
|
478 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
479 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
480 |
+
output_hidden_states = (
|
481 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
482 |
+
)
|
483 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
484 |
+
|
485 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
486 |
+
|
487 |
+
# retrieve input_ids and inputs_embeds
|
488 |
+
if input_ids is not None and inputs_embeds is not None:
|
489 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
490 |
+
elif input_ids is not None:
|
491 |
+
batch_size, seq_length = input_ids.shape
|
492 |
+
elif inputs_embeds is not None:
|
493 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
494 |
+
else:
|
495 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
496 |
+
|
497 |
+
if inputs_embeds is None:
|
498 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
499 |
+
if query_embeds is not None:
|
500 |
+
inputs_embeds = torch.cat([query_embeds, inputs_embeds], dim=1)
|
501 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
502 |
+
|
503 |
+
seq_length_with_past = seq_length
|
504 |
+
past_key_values_length = 0
|
505 |
+
|
506 |
+
if past_key_values is not None:
|
507 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
508 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
509 |
+
|
510 |
+
if position_ids is None:
|
511 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
512 |
+
position_ids = torch.arange(
|
513 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
514 |
+
)
|
515 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
516 |
+
else:
|
517 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
518 |
+
|
519 |
+
# embed positions
|
520 |
+
if attention_mask is None:
|
521 |
+
attention_mask = torch.ones(
|
522 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
523 |
+
)
|
524 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
525 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
526 |
+
)
|
527 |
+
|
528 |
+
hidden_states = inputs_embeds
|
529 |
+
|
530 |
+
if self.gradient_checkpointing and self.training:
|
531 |
+
if use_cache:
|
532 |
+
logger.warning_once(
|
533 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
534 |
+
)
|
535 |
+
use_cache = False
|
536 |
+
|
537 |
+
# decoder layers
|
538 |
+
all_hidden_states = () if output_hidden_states else None
|
539 |
+
all_self_attns = () if output_attentions else None
|
540 |
+
next_decoder_cache = () if use_cache else None
|
541 |
+
|
542 |
+
for idx, decoder_layer in enumerate(self.layers):
|
543 |
+
if output_hidden_states:
|
544 |
+
all_hidden_states += (hidden_states,)
|
545 |
+
|
546 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
547 |
+
|
548 |
+
if self.gradient_checkpointing and self.training:
|
549 |
+
|
550 |
+
def create_custom_forward(module):
|
551 |
+
def custom_forward(*inputs):
|
552 |
+
# None for past_key_value
|
553 |
+
return module(*inputs, output_attentions, None)
|
554 |
+
|
555 |
+
return custom_forward
|
556 |
+
|
557 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
558 |
+
create_custom_forward(decoder_layer),
|
559 |
+
hidden_states,
|
560 |
+
attention_mask,
|
561 |
+
position_ids,
|
562 |
+
None,
|
563 |
+
)
|
564 |
+
else:
|
565 |
+
layer_outputs = decoder_layer(
|
566 |
+
hidden_states,
|
567 |
+
attention_mask=attention_mask,
|
568 |
+
position_ids=position_ids,
|
569 |
+
past_key_value=past_key_value,
|
570 |
+
output_attentions=output_attentions,
|
571 |
+
use_cache=use_cache,
|
572 |
+
)
|
573 |
+
|
574 |
+
hidden_states = layer_outputs[0]
|
575 |
+
|
576 |
+
if use_cache:
|
577 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
578 |
+
|
579 |
+
if output_attentions:
|
580 |
+
all_self_attns += (layer_outputs[1],)
|
581 |
+
|
582 |
+
hidden_states = self.norm(hidden_states)
|
583 |
+
|
584 |
+
# add hidden states from the last decoder layer
|
585 |
+
if output_hidden_states:
|
586 |
+
all_hidden_states += (hidden_states,)
|
587 |
+
|
588 |
+
next_cache = next_decoder_cache if use_cache else None
|
589 |
+
if not return_dict:
|
590 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
591 |
+
return BaseModelOutputWithPast(
|
592 |
+
last_hidden_state=hidden_states,
|
593 |
+
past_key_values=next_cache,
|
594 |
+
hidden_states=all_hidden_states,
|
595 |
+
attentions=all_self_attns,
|
596 |
+
)
|
597 |
+
|
598 |
+
|
599 |
+
class LlamaForCausalLM(LlamaPreTrainedModel):
|
600 |
+
def __init__(self, config):
|
601 |
+
super().__init__(config)
|
602 |
+
self.model = LlamaModel(config)
|
603 |
+
|
604 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
605 |
+
|
606 |
+
# Initialize weights and apply final processing
|
607 |
+
self.post_init()
|
608 |
+
|
609 |
+
def get_input_embeddings(self):
|
610 |
+
return self.model.embed_tokens
|
611 |
+
|
612 |
+
def set_input_embeddings(self, value):
|
613 |
+
self.model.embed_tokens = value
|
614 |
+
|
615 |
+
def get_output_embeddings(self):
|
616 |
+
return self.lm_head
|
617 |
+
|
618 |
+
def set_output_embeddings(self, new_embeddings):
|
619 |
+
self.lm_head = new_embeddings
|
620 |
+
|
621 |
+
def set_decoder(self, decoder):
|
622 |
+
self.model = decoder
|
623 |
+
|
624 |
+
def get_decoder(self):
|
625 |
+
return self.model
|
626 |
+
|
627 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
628 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
629 |
+
def forward(
|
630 |
+
self,
|
631 |
+
input_ids: torch.LongTensor = None,
|
632 |
+
attention_mask: Optional[torch.Tensor] = None,
|
633 |
+
position_ids: Optional[torch.LongTensor] = None,
|
634 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
635 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
636 |
+
query_embeds: Optional[torch.FloatTensor] = None,
|
637 |
+
labels: Optional[torch.LongTensor] = None,
|
638 |
+
use_cache: Optional[bool] = None,
|
639 |
+
output_attentions: Optional[bool] = None,
|
640 |
+
output_hidden_states: Optional[bool] = None,
|
641 |
+
return_dict: Optional[bool] = None,
|
642 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
643 |
+
r"""
|
644 |
+
Args:
|
645 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
646 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
647 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
648 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
649 |
+
|
650 |
+
Returns:
|
651 |
+
|
652 |
+
Example:
|
653 |
+
|
654 |
+
```python
|
655 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
656 |
+
|
657 |
+
>>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
658 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
659 |
+
|
660 |
+
>>> prompt = "Hey, are you consciours? Can you talk to me?"
|
661 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
662 |
+
|
663 |
+
>>> # Generate
|
664 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
665 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
666 |
+
"Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
|
667 |
+
```"""
|
668 |
+
|
669 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
670 |
+
output_hidden_states = (
|
671 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
672 |
+
)
|
673 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
674 |
+
|
675 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
676 |
+
outputs = self.model(
|
677 |
+
input_ids=input_ids,
|
678 |
+
attention_mask=attention_mask,
|
679 |
+
position_ids=position_ids,
|
680 |
+
past_key_values=past_key_values,
|
681 |
+
inputs_embeds=inputs_embeds,
|
682 |
+
query_embeds=query_embeds,
|
683 |
+
use_cache=use_cache,
|
684 |
+
output_attentions=output_attentions,
|
685 |
+
output_hidden_states=output_hidden_states,
|
686 |
+
return_dict=return_dict,
|
687 |
+
)
|
688 |
+
|
689 |
+
hidden_states = outputs[0]
|
690 |
+
logits = self.lm_head(hidden_states)
|
691 |
+
|
692 |
+
loss = None
|
693 |
+
if labels is not None:
|
694 |
+
# Shift so that tokens < n predict n
|
695 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
696 |
+
shift_labels = labels[..., 1:].contiguous()
|
697 |
+
# Flatten the tokens
|
698 |
+
loss_fct = CrossEntropyLoss()
|
699 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
700 |
+
shift_labels = shift_labels.view(-1)
|
701 |
+
# Enable model parallelism
|
702 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
703 |
+
loss = loss_fct(shift_logits, shift_labels)
|
704 |
+
|
705 |
+
if not return_dict:
|
706 |
+
output = (logits,) + outputs[1:]
|
707 |
+
return (loss,) + output if loss is not None else output
|
708 |
+
|
709 |
+
return CausalLMOutputWithPast(
|
710 |
+
loss=loss,
|
711 |
+
logits=logits,
|
712 |
+
past_key_values=outputs.past_key_values,
|
713 |
+
hidden_states=outputs.hidden_states,
|
714 |
+
attentions=outputs.attentions,
|
715 |
+
)
|
716 |
+
|
717 |
+
def prepare_inputs_for_generation(
|
718 |
+
self, input_ids, query_embeds=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
719 |
+
):
|
720 |
+
if past_key_values:
|
721 |
+
input_ids = input_ids[:, -1:]
|
722 |
+
|
723 |
+
position_ids = kwargs.get("position_ids", None)
|
724 |
+
if attention_mask is not None and position_ids is None:
|
725 |
+
# create position_ids on the fly for batch generation
|
726 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
727 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
728 |
+
if past_key_values:
|
729 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
730 |
+
query_embeds = None
|
731 |
+
|
732 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
733 |
+
if inputs_embeds is not None and past_key_values is None:
|
734 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
735 |
+
else:
|
736 |
+
model_inputs = {"input_ids": input_ids}
|
737 |
+
|
738 |
+
model_inputs.update(
|
739 |
+
{
|
740 |
+
"position_ids": position_ids,
|
741 |
+
"query_embeds": query_embeds,
|
742 |
+
"past_key_values": past_key_values,
|
743 |
+
"use_cache": kwargs.get("use_cache"),
|
744 |
+
"attention_mask": attention_mask,
|
745 |
+
}
|
746 |
+
)
|
747 |
+
return model_inputs
|
748 |
+
|
749 |
+
@staticmethod
|
750 |
+
def _reorder_cache(past_key_values, beam_idx):
|
751 |
+
reordered_past = ()
|
752 |
+
for layer_past in past_key_values:
|
753 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
754 |
+
return reordered_past
|
755 |
+
|
model/openllama.py
ADDED
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from header import *
|
2 |
+
import torch.nn.functional as F
|
3 |
+
from .ImageBind import *
|
4 |
+
from .ImageBind import data
|
5 |
+
from .modeling_llama import LlamaForCausalLM
|
6 |
+
from transformers import StoppingCriteria, StoppingCriteriaList
|
7 |
+
|
8 |
+
import torch
|
9 |
+
from torch.nn.utils import rnn
|
10 |
+
|
11 |
+
class StoppingCriteriaSub(StoppingCriteria):
|
12 |
+
|
13 |
+
def __init__(self, stops = [], encounters=1):
|
14 |
+
super().__init__()
|
15 |
+
self.stops = stops
|
16 |
+
self.ENCOUNTERS = encounters
|
17 |
+
|
18 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor):
|
19 |
+
stop_count = 0
|
20 |
+
for stop in self.stops:
|
21 |
+
stop_count = (stop == input_ids[0]).sum().item()
|
22 |
+
if stop_count >= self.ENCOUNTERS:
|
23 |
+
return True
|
24 |
+
return False
|
25 |
+
|
26 |
+
def build_one_instance(tokenizer, conversation):
|
27 |
+
text_list = []
|
28 |
+
turn_num = len(conversation)
|
29 |
+
input_ids, target_ids = [], []
|
30 |
+
for i in range(turn_num):
|
31 |
+
turn = conversation[i]
|
32 |
+
role = turn['from']
|
33 |
+
if i == 0: # the first human turn
|
34 |
+
assert role == 'human'
|
35 |
+
text = '</Img> ' + turn['value'] + '\n### Assistant:'
|
36 |
+
one_input_id = tokenizer(text, add_special_tokens=False).input_ids
|
37 |
+
input_ids += one_input_id
|
38 |
+
target_ids += [-100]*len(one_input_id) # do not perform loss regression on human prompt
|
39 |
+
else:
|
40 |
+
if role == 'human':
|
41 |
+
text = 'Human: ' + turn['value'] + '\n### Assistant:'
|
42 |
+
one_input_id = tokenizer(text, add_special_tokens=False).input_ids
|
43 |
+
input_ids += one_input_id
|
44 |
+
target_ids += [-100]*len(one_input_id)
|
45 |
+
elif role == 'gpt':
|
46 |
+
text = turn['value'] + '\n###'
|
47 |
+
one_input_id = tokenizer(text, add_special_tokens=False).input_ids
|
48 |
+
input_ids += one_input_id
|
49 |
+
target_ids += one_input_id
|
50 |
+
else:
|
51 |
+
raise Exception('Wrong Role!!!')
|
52 |
+
text_list.append(text)
|
53 |
+
assert len(input_ids) == len(target_ids)
|
54 |
+
return text_list, input_ids, target_ids
|
55 |
+
|
56 |
+
def process_batch_instance(tokenizer, batch_of_conversations, max_tgt_len):
|
57 |
+
batch_input_ids, batch_target_ids = [], []
|
58 |
+
for conversation in batch_of_conversations:
|
59 |
+
_, one_input_ids, one_target_ids = build_one_instance(tokenizer, conversation)
|
60 |
+
batch_input_ids.append(torch.LongTensor(one_input_ids))
|
61 |
+
batch_target_ids.append(torch.LongTensor(one_target_ids))
|
62 |
+
input_ids = rnn.pad_sequence(batch_input_ids, batch_first=True, padding_value=tokenizer.pad_token_id)
|
63 |
+
target_ids = rnn.pad_sequence(batch_target_ids, batch_first=True, padding_value=-100)
|
64 |
+
assert input_ids.size() == target_ids.size()
|
65 |
+
input_ids = input_ids[:,:max_tgt_len]
|
66 |
+
target_ids = target_ids[:,:max_tgt_len]
|
67 |
+
attention_mask = input_ids.ne(tokenizer.pad_token_id)
|
68 |
+
assert attention_mask.size() == input_ids.size()
|
69 |
+
return input_ids, target_ids, attention_mask.long()
|
70 |
+
|
71 |
+
PROMPT_START = '### Human: <Img>'
|
72 |
+
class OpenLLAMAPEFTModel(nn.Module):
|
73 |
+
|
74 |
+
'''LoRA for LLaMa model'''
|
75 |
+
|
76 |
+
def __init__(self, **args):
|
77 |
+
super(OpenLLAMAPEFTModel, self).__init__()
|
78 |
+
self.args = args
|
79 |
+
imagebind_ckpt_path = args['imagebind_ckpt_path']
|
80 |
+
vicuna_ckpt_path = args['vicuna_ckpt_path']
|
81 |
+
max_tgt_len = args['max_tgt_len']
|
82 |
+
stage = args['stage']
|
83 |
+
|
84 |
+
print (f'Initializing visual encoder from {imagebind_ckpt_path} ...')
|
85 |
+
self.visual_encoder, self.visual_hidden_size = \
|
86 |
+
imagebind_model.imagebind_huge(pretrained=True, store_path=imagebind_ckpt_path)
|
87 |
+
# free vision encoder
|
88 |
+
for name, param in self.visual_encoder.named_parameters():
|
89 |
+
param.requires_grad = False
|
90 |
+
self.visual_encoder.eval()
|
91 |
+
print ('Visual encoder initialized.')
|
92 |
+
|
93 |
+
print (f'Initializing language decoder from {vicuna_ckpt_path} ...')
|
94 |
+
# add the lora module
|
95 |
+
peft_config = LoraConfig(
|
96 |
+
task_type=TaskType.CAUSAL_LM,
|
97 |
+
inference_mode=False,
|
98 |
+
r=self.args['lora_r'],
|
99 |
+
lora_alpha=self.args['lora_alpha'],
|
100 |
+
lora_dropout=self.args['lora_dropout'],
|
101 |
+
target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj']
|
102 |
+
)
|
103 |
+
|
104 |
+
self.llama_model = LlamaForCausalLM.from_pretrained(vicuna_ckpt_path)
|
105 |
+
self.llama_model = get_peft_model(self.llama_model, peft_config)
|
106 |
+
self.llama_model.print_trainable_parameters()
|
107 |
+
|
108 |
+
self.llama_tokenizer = LlamaTokenizer.from_pretrained(vicuna_ckpt_path, use_fast=False)
|
109 |
+
self.llama_tokenizer.pad_token = self.llama_tokenizer.eos_token
|
110 |
+
self.llama_tokenizer.padding_side = "right"
|
111 |
+
print ('Language decoder initialized.')
|
112 |
+
|
113 |
+
self.llama_proj = nn.Linear(
|
114 |
+
self.visual_hidden_size, self.llama_model.config.hidden_size
|
115 |
+
)
|
116 |
+
|
117 |
+
self.max_tgt_len = max_tgt_len
|
118 |
+
self.device = torch.cuda.current_device()
|
119 |
+
|
120 |
+
def encode_video(self, video_paths):
|
121 |
+
inputs = {ModalityType.VISION: data.load_and_transform_video_data(video_paths, self.device)}
|
122 |
+
# convert into visual dtype
|
123 |
+
inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
|
124 |
+
with torch.no_grad():
|
125 |
+
embeddings = self.visual_encoder(inputs)
|
126 |
+
video_embeds = embeddings[ModalityType.VISION] # bsz x 1024
|
127 |
+
inputs_llama = self.llama_proj(video_embeds).unsqueeze(1) # bsz x 1 x llama_size
|
128 |
+
atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
|
129 |
+
return inputs_llama, atts_llama
|
130 |
+
|
131 |
+
def encode_audio(self, audio_paths):
|
132 |
+
inputs = {ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, self.device)}
|
133 |
+
# convert into visual dtype
|
134 |
+
inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
|
135 |
+
with torch.no_grad():
|
136 |
+
embeddings = self.visual_encoder(inputs)
|
137 |
+
audio_embeds = embeddings[ModalityType.AUDIO] # bsz x 1024
|
138 |
+
inputs_llama = self.llama_proj(audio_embeds).unsqueeze(1) # bsz x 1 x llama_size
|
139 |
+
atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
|
140 |
+
return inputs_llama, atts_llama
|
141 |
+
|
142 |
+
def encode_thermal(self, thermal_paths):
|
143 |
+
inputs = {ModalityType.THERMAL: data.load_and_transform_thermal_data(thermal_paths, self.device)}
|
144 |
+
# convert into visual dtype
|
145 |
+
inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
|
146 |
+
with torch.no_grad():
|
147 |
+
embeddings = self.visual_encoder(inputs)
|
148 |
+
image_embeds = embeddings['thermal'] # bsz x 1024
|
149 |
+
inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
|
150 |
+
atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
|
151 |
+
return inputs_llama, atts_llama
|
152 |
+
|
153 |
+
def encode_image(self, image_paths):
|
154 |
+
inputs = {ModalityType.VISION: data.load_and_transform_vision_data(image_paths, self.device)}
|
155 |
+
# convert into visual dtype
|
156 |
+
inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
|
157 |
+
with torch.no_grad():
|
158 |
+
embeddings = self.visual_encoder(inputs)
|
159 |
+
image_embeds = embeddings['vision'] # bsz x 1024
|
160 |
+
inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
|
161 |
+
atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
|
162 |
+
return inputs_llama, atts_llama
|
163 |
+
|
164 |
+
def prompt_wrap(self, img_embeds, input_ids, target_ids, attention_mask):
|
165 |
+
'''
|
166 |
+
input_ids, target_ids, attention_mask: bsz x s2
|
167 |
+
'''
|
168 |
+
input_ids = input_ids.to(self.device) # bsz x s2
|
169 |
+
target_ids = target_ids.to(self.device) # bsz x s2
|
170 |
+
attention_mask = attention_mask.to(self.device) # bsz x s2
|
171 |
+
|
172 |
+
batch_size = img_embeds.shape[0]
|
173 |
+
p_before = PROMPT_START
|
174 |
+
p_before_tokens = self.llama_tokenizer(p_before,
|
175 |
+
return_tensors="pt", add_special_tokens=False).to(self.device)
|
176 |
+
# peft model need deeper call
|
177 |
+
p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s1 x embed_dim
|
178 |
+
p_after_embeds = self.llama_model.model.model.embed_tokens(input_ids).expand(batch_size, -1, -1) # bsz x s2 x embed_dim
|
179 |
+
bos = torch.ones([batch_size, 1],
|
180 |
+
dtype=p_before_tokens.input_ids.dtype,
|
181 |
+
device=p_before_tokens.input_ids.device) * self.llama_tokenizer.bos_token_id # bsz x 1
|
182 |
+
bos_embeds = self.llama_model.model.model.embed_tokens(bos) # bsz x 1 x embed_dim
|
183 |
+
inputs_embeds = torch.cat([bos_embeds, p_before_embeds, img_embeds, p_after_embeds], dim=1) # bsz x (1+s1+1+s2) x embed_dim
|
184 |
+
|
185 |
+
# create targets
|
186 |
+
empty_targets = (
|
187 |
+
torch.ones([batch_size, 1+p_before_embeds.size()[1]+1], # 1 (bos) + s1 + 1 (image vector)
|
188 |
+
dtype=torch.long).to(self.device).fill_(-100)
|
189 |
+
) # bsz x (1 + s1 + 1)
|
190 |
+
targets = torch.cat([empty_targets, target_ids], dim=1) # bsz x (1 + s1 + 1 + s2)
|
191 |
+
assert inputs_embeds.size()[1] == targets.size()[1]
|
192 |
+
|
193 |
+
atts_prefix = torch.ones([batch_size, 1+p_before_embeds.size()[1]+1], dtype=torch.long).to(self.device) # bsz x (1 + s1 +1)
|
194 |
+
attention_mask = torch.cat([atts_prefix, attention_mask], dim=1)
|
195 |
+
assert attention_mask.size() == targets.size() # bsz x (1 + s1 + 1 + s2)
|
196 |
+
return inputs_embeds, targets, attention_mask
|
197 |
+
|
198 |
+
def forward(self, inputs):
|
199 |
+
image_paths = inputs['image_paths']
|
200 |
+
img_embeds, _ = self.encode_image(image_paths)
|
201 |
+
|
202 |
+
output_texts = inputs['output_texts']
|
203 |
+
input_ids, target_ids, attention_mask = process_batch_instance(self.llama_tokenizer, output_texts, self.max_tgt_len)
|
204 |
+
inputs_embeds, targets, attention_mask = self.prompt_wrap(img_embeds, input_ids, target_ids, attention_mask)
|
205 |
+
|
206 |
+
outputs = self.llama_model(
|
207 |
+
inputs_embeds=inputs_embeds,
|
208 |
+
attention_mask=attention_mask,
|
209 |
+
return_dict=True,
|
210 |
+
labels=targets,
|
211 |
+
)
|
212 |
+
loss = outputs.loss
|
213 |
+
# calculate the token accuarcy
|
214 |
+
chosen_tokens = torch.max(outputs.logits, dim=-1)[1][:, 1:-1] # [B, S-1]
|
215 |
+
labels = targets[:, 2:]
|
216 |
+
gen_acc = (chosen_tokens.reshape(-1) == labels.reshape(-1)).to(torch.long) # [B*S]
|
217 |
+
valid_mask = (labels != -100).reshape(-1)
|
218 |
+
valid_tokens = gen_acc & valid_mask # [B*S]
|
219 |
+
gen_acc = valid_tokens.sum().item() / valid_mask.sum().item()
|
220 |
+
return loss, gen_acc
|
221 |
+
|
222 |
+
def extract_multimodal_feature(self, inputs):
|
223 |
+
features = []
|
224 |
+
if inputs['image_paths']:
|
225 |
+
image_embeds, _ = self.encode_image(inputs['image_paths'])
|
226 |
+
features.append(image_embeds)
|
227 |
+
if inputs['audio_paths']:
|
228 |
+
audio_embeds, _ = self.encode_audio(inputs['audio_paths'])
|
229 |
+
features.append(audio_embeds)
|
230 |
+
if inputs['video_paths']:
|
231 |
+
video_embeds, _ = self.encode_video(inputs['video_paths'])
|
232 |
+
features.append(video_embeds)
|
233 |
+
if inputs['thermal_paths']:
|
234 |
+
thermal_embeds, _ = self.encode_thermal(inputs['thermal_paths'])
|
235 |
+
features.append(thermal_embeds)
|
236 |
+
|
237 |
+
feature_embeds = torch.cat(features).sum(dim=0).unsqueeze(0)
|
238 |
+
return feature_embeds
|
239 |
+
|
240 |
+
def prepare_generation_embedding(self, inputs):
|
241 |
+
prompt = inputs['prompt']
|
242 |
+
if len(inputs['modality_embeds']) == 1:
|
243 |
+
feature_embeds = inputs['modality_embeds'][0]
|
244 |
+
else:
|
245 |
+
feature_embeds = self.extract_multimodal_feature(inputs)
|
246 |
+
inputs['modality_embeds'].append(feature_embeds)
|
247 |
+
|
248 |
+
batch_size = feature_embeds.shape[0]
|
249 |
+
p_before = PROMPT_START
|
250 |
+
p_before_tokens = self.llama_tokenizer(p_before,
|
251 |
+
return_tensors="pt", add_special_tokens=False).to(self.device)
|
252 |
+
p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s1 x embed_dim
|
253 |
+
text = '</Img> ' + prompt + '\n### Assistant:'
|
254 |
+
p_after_tokens = self.llama_tokenizer(text, add_special_tokens=False, return_tensors='pt').to(self.device)
|
255 |
+
p_after_embeds = self.llama_model.model.model.embed_tokens(p_after_tokens.input_ids).expand(batch_size, -1, -1) # bsz x s1 x embed_dim
|
256 |
+
bos = torch.ones([batch_size, 1],
|
257 |
+
dtype=p_before_tokens.input_ids.dtype,
|
258 |
+
device=p_before_tokens.input_ids.device) * self.llama_tokenizer.bos_token_id # bsz x 1
|
259 |
+
bos_embeds = self.llama_model.model.model.embed_tokens(bos) # bsz x 1 x embed_dim
|
260 |
+
inputs_embeds = torch.cat([bos_embeds, p_before_embeds, feature_embeds, p_after_embeds], dim=1) # bsz x (1+s1+1+s2) x embed_dim
|
261 |
+
return inputs_embeds
|
262 |
+
|
263 |
+
def generate(self, inputs):
|
264 |
+
'''
|
265 |
+
inputs = {
|
266 |
+
'image_paths': optional,
|
267 |
+
'audio_paths': optional
|
268 |
+
'video_paths': optional
|
269 |
+
'thermal_paths': optional
|
270 |
+
'mode': generation mode,
|
271 |
+
'prompt': human input prompt,
|
272 |
+
'max_tgt_len': generation length,
|
273 |
+
'top_p': top_p,
|
274 |
+
'temperature': temperature
|
275 |
+
'modality_embeds': None or torch.tensor
|
276 |
+
'modality_cache': save the image cache
|
277 |
+
}
|
278 |
+
'''
|
279 |
+
input_embeds = self.prepare_generation_embedding(inputs)
|
280 |
+
stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=[2277], encounters=1)])
|
281 |
+
outputs = self.llama_model.generate(
|
282 |
+
inputs_embeds=input_embeds,
|
283 |
+
max_new_tokens=inputs['max_tgt_len'],
|
284 |
+
top_p=inputs['top_p'],
|
285 |
+
temperature=inputs['temperature'],
|
286 |
+
do_sample=True,
|
287 |
+
use_cache=True,
|
288 |
+
stopping_criteria=stopping_criteria,
|
289 |
+
)
|
290 |
+
output_text = self.llama_tokenizer.decode(outputs[0][:-2], skip_special_tokens=True)
|
291 |
+
return output_text
|
292 |
+
|
pretrained_ckpt/README.md
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 1. Prepare Vicuna Checkpoint:
|
2 |
+
|
3 |
+
The language decoder of PandaGPT is based on Vicuna version 0. Given the distribution license of LLaMA, you need to restore the weights of Vicuna manually. To restore the weights, please follow the instructions below. In the following, we showcase how to restore the 7B version of Vicuna v0. To obtain the 13B version of Vicuna, you can take similar procedures.
|
4 |
+
|
5 |
+
## 1.1. Obtain LLaMA Weights:
|
6 |
+
* Request the weights of LLaMA from Meta using [this form](https://docs.google.com/forms/d/e/1FAIpQLSfqNECQnMkycAp2jP4Z9TFX0cGR4uf7b_fBxjY_OjhJILlKGA/viewform).
|
7 |
+
* After obtaining the weights of a specific LLaMA (e.g. 7B, 13B), following [instructions](https://huggingface.co/docs/transformers/main/model_doc/llama) provided by Huggingface to convert it into Huggingface format.
|
8 |
+
|
9 |
+
> **** After conversion, the directory should look like:
|
10 |
+
|
11 |
+
.
|
12 |
+
└── ./{path_to_llama_weights}/
|
13 |
+
├── config.json
|
14 |
+
├── generation_config.json
|
15 |
+
├── pytorch_model-00001-of-00002.bin
|
16 |
+
├── pytorch_model-00002-of-00002.bin
|
17 |
+
├── pytorch_model.bin.index.json
|
18 |
+
├── special_tokens_map.json
|
19 |
+
├── tokenizer.model
|
20 |
+
└── tokenizer_config.json
|
21 |
+
|
22 |
+
`{path_to_llama_weights}` is where you store the checkpoints.
|
23 |
+
|
24 |
+
|
25 |
+
## 1.2. Obtain the Delta Weights of Vicuna:
|
26 |
+
|
27 |
+
Then, you should download the delta weights of Vicuna provided by the original authors. You can find the corresponding links to 7B/13B Vicuna models in the table below.
|
28 |
+
|
29 |
+
|**Model Size**|**Delta Weights Address**|**Version**|
|
30 |
+
|:-------------:|:-------------:|:-------------:|
|
31 |
+
|7B|[[Link]](https://huggingface.co/lmsys/vicuna-7b-delta-v0)|0|
|
32 |
+
|13B|[[Link]](https://huggingface.co/lmsys/vicuna-13b-delta-v0)|0|
|
33 |
+
|
34 |
+
|
35 |
+
|
36 |
+
> **** After conversion, the directory should look like:
|
37 |
+
|
38 |
+
.
|
39 |
+
└── ./{path_to_delta_vicuna_weights}/
|
40 |
+
├── config.json
|
41 |
+
├── generation_config.json
|
42 |
+
├── pytorch_model-00001-of-00002.bin
|
43 |
+
├── pytorch_model-00002-of-00002.bin
|
44 |
+
├── pytorch_model.bin.index.json
|
45 |
+
├── special_tokens_map.json
|
46 |
+
├── tokenizer.model
|
47 |
+
└── tokenizer_config.json
|
48 |
+
|
49 |
+
`{path_to_delta_vicuna_weights}` is where you store the delta weights of Vicuna.
|
50 |
+
|
51 |
+
## 1.3. Combine the Weights:
|
52 |
+
|
53 |
+
When the two sets of weights are ready, you can combine them using tools from the Vicuna team.
|
54 |
+
|
55 |
+
First, install the required library.
|
56 |
+
```yaml
|
57 |
+
pip install git+https://github.com/lm-sys/FastChat.git@v0.1.10
|
58 |
+
```
|
59 |
+
|
60 |
+
Then, run the following command.
|
61 |
+
```yaml
|
62 |
+
python -m fastchat.model.apply_delta --base {path_to_llama_weights} --target ./vicuna_ckpt/7b_v0/ --delta {path_to_delta_vicuna_weights}
|
63 |
+
```
|
64 |
+
|
65 |
+
> **** Now, the final weights are ready as:
|
66 |
+
|
67 |
+
.
|
68 |
+
└── ./vicuna_ckpt/7b_v0/
|
69 |
+
├── config.json
|
70 |
+
├── generation_config.json
|
71 |
+
├── pytorch_model-00001-of-00002.bin
|
72 |
+
├── pytorch_model-00002-of-00002.bin
|
73 |
+
├── pytorch_model.bin.index.json
|
74 |
+
├── special_tokens_map.json
|
75 |
+
├── tokenizer.model
|
76 |
+
└── tokenizer_config.json
|
77 |
+
|
78 |
+
|
pretrained_ckpt/imagebind_ckpt/empty.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
empty placeholder
|
pretrained_ckpt/pandagpt_ckpt/13b/empty.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
empty placeholder
|