Camil Ziane commited on
Commit
74b17e0
·
1 Parent(s): fa042b8

init space

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. TinyLLaVA_Factory/.gitignore +63 -0
  2. TinyLLaVA_Factory/CUSTOM_FINETUNE.md +96 -0
  3. TinyLLaVA_Factory/LICENSE +201 -0
  4. TinyLLaVA_Factory/README.md +428 -0
  5. TinyLLaVA_Factory/assets/architecture.jpg +0 -0
  6. TinyLLaVA_Factory/pyproject.toml +38 -0
  7. TinyLLaVA_Factory/scripts/convert_answer_to_mmmu.py +31 -0
  8. TinyLLaVA_Factory/scripts/convert_gqa_for_eval.py +18 -0
  9. TinyLLaVA_Factory/scripts/convert_mmvet_for_eval.py +18 -0
  10. TinyLLaVA_Factory/scripts/convert_vqav2_for_submission.py +56 -0
  11. TinyLLaVA_Factory/scripts/eval/gqa.sh +43 -0
  12. TinyLLaVA_Factory/scripts/eval/mme.sh +22 -0
  13. TinyLLaVA_Factory/scripts/eval/mmmu.sh +21 -0
  14. TinyLLaVA_Factory/scripts/eval/mmvet.sh +19 -0
  15. TinyLLaVA_Factory/scripts/eval/pope.sh +18 -0
  16. TinyLLaVA_Factory/scripts/eval/sqa.sh +20 -0
  17. TinyLLaVA_Factory/scripts/eval/textvqa.sh +18 -0
  18. TinyLLaVA_Factory/scripts/eval/vqav2.sh +38 -0
  19. TinyLLaVA_Factory/scripts/train/custom_finetune.sh +45 -0
  20. TinyLLaVA_Factory/scripts/train/finetune.sh +64 -0
  21. TinyLLaVA_Factory/scripts/train/gemma/finetune_gemma.sh +64 -0
  22. TinyLLaVA_Factory/scripts/train/gemma/pretrain_gemma.sh +62 -0
  23. TinyLLaVA_Factory/scripts/train/gemma/train_gemma.sh +17 -0
  24. TinyLLaVA_Factory/scripts/train/lora/finetune_lora.sh +66 -0
  25. TinyLLaVA_Factory/scripts/train/lora/finetune_qlora.sh +66 -0
  26. TinyLLaVA_Factory/scripts/train/lora/train_phi_lora.sh +18 -0
  27. TinyLLaVA_Factory/scripts/train/lora/train_phi_qlora.sh +18 -0
  28. TinyLLaVA_Factory/scripts/train/openelm/finetune_openelm.sh +64 -0
  29. TinyLLaVA_Factory/scripts/train/openelm/pretrain_openelm.sh +62 -0
  30. TinyLLaVA_Factory/scripts/train/openelm/train_openelm.sh +17 -0
  31. TinyLLaVA_Factory/scripts/train/pretrain.sh +62 -0
  32. TinyLLaVA_Factory/scripts/train/qwen2/finetune_qwen2.sh +64 -0
  33. TinyLLaVA_Factory/scripts/train/qwen2/pretrain_qwen2.sh +62 -0
  34. TinyLLaVA_Factory/scripts/train/qwen2/readme.md +1 -0
  35. TinyLLaVA_Factory/scripts/train/qwen2/train_qwen2_base.sh +17 -0
  36. TinyLLaVA_Factory/scripts/train/qwen2/train_qwen2_instruct.sh +17 -0
  37. TinyLLaVA_Factory/scripts/train/share/finetune_share.sh +64 -0
  38. TinyLLaVA_Factory/scripts/train/share/pretrain_share.sh +63 -0
  39. TinyLLaVA_Factory/scripts/train/share/train_phi_share.sh +21 -0
  40. TinyLLaVA_Factory/scripts/train/train_mof.sh +17 -0
  41. TinyLLaVA_Factory/scripts/train/train_phi.sh +17 -0
  42. TinyLLaVA_Factory/scripts/train/train_stablelm.sh +17 -0
  43. TinyLLaVA_Factory/scripts/train/train_tinyllama.sh +17 -0
  44. TinyLLaVA_Factory/scripts/zero2.json +23 -0
  45. TinyLLaVA_Factory/scripts/zero3.json +28 -0
  46. TinyLLaVA_Factory/tinyllava/__init__.py +0 -0
  47. TinyLLaVA_Factory/tinyllava/data/__init__.py +4 -0
  48. TinyLLaVA_Factory/tinyllava/data/dataset.py +128 -0
  49. TinyLLaVA_Factory/tinyllava/data/image_preprocess.py +70 -0
  50. TinyLLaVA_Factory/tinyllava/data/template/__init__.py +29 -0
TinyLLaVA_Factory/.gitignore ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are some examples of commonly ignored file patterns.
2
+ # You should customize this list as applicable to your project.
3
+ # Learn more about .gitignore:
4
+ # https://www.atlassian.com/git/tutorials/saving-changes/gitignore
5
+
6
+ # Node artifact files
7
+ node_modules/
8
+ dist/
9
+
10
+ # Compiled Java class files
11
+ *.class
12
+
13
+ # Compiled Python bytecode
14
+ *.py[cod]
15
+
16
+ # Log files
17
+ *.log
18
+
19
+ # Package files
20
+ *.jar
21
+
22
+ # Maven
23
+ target/
24
+ dist/
25
+
26
+ # JetBrains IDE
27
+ .idea/
28
+
29
+ # Unit test reports
30
+ TEST*.xml
31
+
32
+ # Generated by MacOS
33
+ .DS_Store
34
+
35
+ # Generated by Windows
36
+ Thumbs.db
37
+
38
+ # Applications
39
+ *.app
40
+ *.exe
41
+ *.war
42
+
43
+ # Large media files
44
+ *.mp4
45
+ *.tiff
46
+ *.avi
47
+ *.flv
48
+ *.mov
49
+ *.wmv
50
+
51
+ #
52
+ .ipynb_checkpoints
53
+ __pycache__
54
+ *.egg-info
55
+ .vscode/*
56
+ .idea/*
57
+ playground/
58
+ wandb/*
59
+ checkpoints/*
60
+ .ipynb_checkpoints/*
61
+ scripts/.ipynb_checkpoints/*
62
+ test/*
63
+ output/*
TinyLLaVA_Factory/CUSTOM_FINETUNE.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Finetune TinyLLaVA with Custom Datasets
2
+
3
+ Given the needs of finetuning with custom datasets, we provide a tutorial on how to custom finetune on our trained model, e.g. tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B (HF path).
4
+
5
+ ## Dataset Format
6
+
7
+ Convert your data to a JSON file of a List of all samples. Sample metadata should contain `id` (a unique identifier), `image` (the path to the image), and `conversations` (the conversation data between human and AI).
8
+
9
+ Here's an example of the [pokemon dataset](https://huggingface.co/datasets/lambdalabs/pokemon-blip-captions) turned into the data format:
10
+
11
+ ```json
12
+ [
13
+ {
14
+ "id": "meiKqU2auAVK2vrtLhKGoJ",
15
+ "image": "pokemon/image/meiKqU2auAVK2vrtLhKGoJ.jpg",
16
+ "conversations": [
17
+ {
18
+ "from": "human",
19
+ "value": "<image>\nProvide a brief description of the given image."
20
+ },
21
+ {
22
+ "from": "gpt",
23
+ "value": "a drawing of a green pokemon with red eyes"
24
+ }
25
+ ]
26
+ }
27
+ ]
28
+ ```
29
+
30
+ <details>
31
+ You can use the following scripts to convert the Pokemon dataset to the above data format.
32
+ <summary>converting data format</summary>
33
+
34
+ ```python
35
+ import shortuuid
36
+ from datasets import load_dataset
37
+ from PIL import Image
38
+ import random
39
+ import json
40
+ import tqdm
41
+ import os
42
+
43
+ ds = load_dataset('lambdalabs/pokemon-blip-captions')
44
+ pokemon_data = []
45
+
46
+ pokemon_image_path = '/path/to/your/data/pokemon/image'
47
+ pokemon_data_path = '/path/to/your/pokemon_blip_captions.json'
48
+
49
+ description_list = [
50
+ "Describe the image concisely.",
51
+ "Provide a brief description of the given image.",
52
+ "Offer a succinct explanation of the picture presented.",
53
+ "Summarize the visual content of the image.",
54
+ "Give a short and clear explanation of the subsequent image.",
55
+ "Share a concise interpretation of the image provided.",
56
+ "Present a compact description of the photo's key features.",
57
+ "Relay a brief, clear account of the picture shown.",
58
+ "Render a clear and concise summary of the photo.",
59
+ "Write a terse but informative summary of the picture.",
60
+ "Create a compact narrative representing the image presented."
61
+ ]
62
+
63
+ for sample in tqdm.tqdm(ds['train']):
64
+ uuid = shortuuid.uuid()
65
+ sample_dict = dict()
66
+ sample_dict['id'] = uuid
67
+ sample_dict['image'] = 'pokemon/image/' + uuid + '.jpg'
68
+ sample['image'].save(os.path.join(pokemon_image_path, uuid + '.jpg'))
69
+ conversations = [
70
+ {"from": "human", "value": "<image>\n" + random.choice(description_list)},
71
+ {"from": "gpt", "value": sample['text']}
72
+ ]
73
+ sample_dict['conversations'] = conversations
74
+ pokemon_data.append(sample_dict)
75
+
76
+ with open(pokemon_data_path, 'w') as f:
77
+ json.dump(pokemon_data, f, indent=4)
78
+ ```
79
+
80
+ </details>
81
+
82
+ ## Custom Finetune
83
+ After acquiring the dataset following the above data format, you can finetune our trained model TinyLLaVA-Phi-2-SigLIP-3.1B checkpoint by using lora.
84
+
85
+ - Replace data paths and `output_dir` with yours in `scripts/train/custom_finetune.sh`
86
+ - Adjust your GPU ids (localhost) and `per_device_train_batch_size` in `scripts/train/custom_finetune.sh`.
87
+
88
+ ```bash
89
+ bash scripts/train/custom_finetune.sh
90
+ ```
91
+
92
+ ## Evaluation with Custom Finetuned Model
93
+ All of the models trained by TinyLLaVA Factory have the same evaluation procedure, no matter it is trained through custom finetune or through normal training. Please see the [Evaluation](https://tinyllava-factory.readthedocs.io/en/latest/Evaluation.html) section in our Doc.
94
+
95
+
96
+
TinyLLaVA_Factory/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 [TinyLLaVA]
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.
TinyLLaVA_Factory/README.md ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h2 align="center"> <a href="https://arxiv.org/abs/2402.14289">TinyLLaVA Factory</a><h5 align="center">
2
+
3
+ [![hf_space](https://img.shields.io/badge/🤗-%20Open%20In%20HF-blue.svg)](https://huggingface.co/tinyllava) [![arXiv](https://img.shields.io/badge/Arxiv-2402.14289-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2402.14289) [![arXiv](https://img.shields.io/badge/Arxiv-2405.11788-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2405.11788)[![License](https://img.shields.io/badge/License-Apache%202.0-yellow)](https://github.com/TinyLLaVA/TinyLLaVA_Factory/blob/main/LICENSE) [![Doc](https://img.shields.io/badge/Doc-Document-logo=read%20the%20docs&logoColor=white&label=Doc)](https://tinyllava-factory.readthedocs.io/en/latest/) [![Demo](https://img.shields.io/badge/Demo-Demo-red.svg)](http://8843843nmph5.vicp.fun/#/)
4
+
5
+ ![architecture](./assets/architecture.jpg)
6
+
7
+ ## &#x1F389; News
8
+ * **[2024.08.13]** A simple [visualizaiton tool](https://github.com/TinyLLaVA/TinyLLaVA_Factory/tree/main/tinyllava_visualizer) for interpreting the prediction of TinyLLaVA is added.
9
+ * **[2024.05.21]** Our paper: [TinyLLaVA Factory: A Modularized Codebase for Small-scale Large Multimodal Models](https://arxiv.org/abs/2405.11788) is released!
10
+ * **[2024.05.15]** [TinyLLaVA Factory](https://github.com/TinyLLaVA/TinyLLaVA_Factory), our new codebase, is released! **Note that the old codebase, TinyLLaVABench, is moved to the [tinyllava_bench](https://github.com/TinyLLaVA/TinyLLaVA_Factory/tree/tinyllava_bench) branch.**
11
+ * **[2024.05.04]** [TinyLLaVA Demo](http://8843843nmph5.vicp.fun/#/) is released!
12
+ * **[2024.02.21]** Our paper: [TinyLLaVA: A Framework of Small-scale Large Multimodal Models](https://arxiv.org/abs/2402.14289) is released!
13
+
14
+ ## &#x1F525; Takeaways
15
+ - Our best model, [TinyLLaVA-Phi-2-SigLIP-3.1B](https://huggingface.co/tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B), achieves better overall performance against existing 7B models such as LLaVA-1.5 and Qwen-VL.
16
+
17
+ - TinyLLaVA Factory is an open-source modular codebase for small-scale large multimodal models (LMMs), implemented in PyTorch and HuggingFace, with a focus on simplicity of code implementations, extensibility of new features, and reproducibility of training results.
18
+
19
+ - With TinyLLaVA Factory, you can customize your own large multimodal models with less coding effort and less coding mistakes.
20
+
21
+ - TinyLLaVA Factory integrates a suite of cutting-edge models and methods.
22
+
23
+ - LLM currently supports **OpenELM**, **TinyLlama**, **StableLM**, **Qwen**, **Gemma**, and **Phi**.
24
+
25
+ - Vision tower currently supports **CLIP,** **SigLIP**, **Dino**, and **combination of CLIP and Dino**.
26
+
27
+ - Connector currently supports **MLP**, **Qformer**, and **Resampler**.
28
+
29
+ - Training Recipe currently supports **Frozen/Fully/Partially tuning** and **LoRA/QLoRA tuning**.
30
+
31
+ - The password to access our demo is '1234'.
32
+
33
+ ## Contents
34
+
35
+ - [🎉 News](#-news)
36
+ - [🔥 Takeaways](#-takeaways)
37
+ - [Contents](#contents)
38
+ - [Installation and Requirements](#installation-and-requirements)
39
+ - [Upgrade to the latest code base](#upgrade-to-the-latest-code-base)
40
+ - [Get Started](#get-started)
41
+ - [1. Data Preparation](#1-data-preparation)
42
+ - [2. Train](#2-train)
43
+ - [3. Evaluation](#3-evaluation)
44
+ - [Model Zoo](#model-zoo)
45
+ - [Trained Models](#trained-models)
46
+ - [Model Performance](#model-performance)
47
+ - [Legacy Models](#legacy-models)
48
+ - [Launch Demo Locally](#launch-demo-locally)
49
+ - [Gradio Web Demo](#gradio-web-demo)
50
+ - [CLI Inference](#cli-inference)
51
+ - [Quick Inference Scripts](#quick-inference-scripts)
52
+ - [Custom Finetune](#custom-finetune)
53
+ - [Customize Your Own Large Multimodel Models](#customize-your-own-large-multimodel-models)
54
+ - [LLM](#llm)
55
+ - [Vision Tower](#vision-tower)
56
+ - [Connector](#connector)
57
+ - [Acknowledgement](#acknowledgement)
58
+ - [Contact](#contact)
59
+ - [✏ Citation](#-citation)
60
+ - [❤️ Community efforts](#️-community-efforts)
61
+
62
+
63
+ ## Installation and Requirements
64
+
65
+ Please note that our environment requirements are different from LLaVA's environment requirements. We strongly recommend you create the environment from scratch as follows.
66
+
67
+ 1. Clone this repository and navigate to the folder
68
+ ```bash
69
+ git clone https://github.com/TinyLLaVA/TinyLLaVA_Factory.git
70
+ cd TinyLLaVA_Factory
71
+ ```
72
+
73
+ 2. Create a conda environment, activate it and install Packages
74
+ ```Shell
75
+ conda create -n tinyllava_factory python=3.10 -y
76
+ conda activate tinyllava_factory
77
+ pip install --upgrade pip # enable PEP 660 support
78
+ pip install -e .
79
+ ```
80
+
81
+ 3. Install additional packages
82
+ ```Shell
83
+ pip install flash-attn --no-build-isolation
84
+ ```
85
+ #### Upgrade to the latest code base
86
+
87
+ ```Shell
88
+ git pull
89
+ pip install -e .
90
+ ```
91
+
92
+ ## Get Started
93
+
94
+ #### 1. Data Preparation
95
+
96
+ Please refer to the [Data Preparation](https://tinyllava-factory.readthedocs.io/en/latest/Prepare%20Datasets.html) section in our [Documenation](https://tinyllava-factory.readthedocs.io/en/latest/).
97
+
98
+ #### 2. Train
99
+
100
+ Here's an example for training a LMM using Phi-2.
101
+
102
+ - Replace data paths with yours in `scripts/train/train_phi.sh`
103
+ - Replace `output_dir` with yours in `scripts/train/pretrain.sh`
104
+ - Replace `pretrained_model_path` and `output_dir` with yours in `scripts/train/finetune.sh`
105
+ - Adjust your GPU ids (localhost) and `per_device_train_batch_size` in `scripts/train/pretrain.sh` and `scripts/train/finetune.sh`
106
+
107
+ ```bash
108
+ bash scripts/train/train_phi.sh
109
+ ```
110
+
111
+ Important hyperparameters used in pretraining and finetuning are provided below.
112
+
113
+ | Training Stage | Global Batch Size | Learning rate | conv_version |
114
+ | -------------- | :---------------: | :-----------: | :----------: |
115
+ | Pretraining | 256 | 1e-3 | pretrain |
116
+ | Finetuning | 128 | 2e-5 | phi |
117
+
118
+ **Tips:**
119
+
120
+ Global Batch Size = num of GPUs * `per_device_train_batch_size` * `gradient_accumulation_steps`, we recommand you always keep global batch size and learning rate as above except for lora tuning your model.
121
+
122
+ `conv_version` is a hyperparameter used for choosing different chat templates for different LLMs. In the pretraining stage, `conv_version` is the same for all LLMs, using `pretrain`. In the finetuning stage, we use
123
+
124
+ `phi` for Phi-2, StableLM, Qwen-1.5
125
+
126
+ `llama` for TinyLlama, OpenELM
127
+
128
+ `gemma` for Gemma
129
+
130
+ #### 3. Evaluation
131
+
132
+ Please refer to the [Evaluation](https://tinyllava-factory.readthedocs.io/en/latest/Evaluation.html) section in our [Documenation](https://tinyllava-factory.readthedocs.io/en/latest/Evaluation.html).
133
+
134
+ ## Model Zoo
135
+
136
+ ### Trained Models
137
+
138
+ which are trained using TinyLLaVA Factory.
139
+
140
+ - [TinyLLaVA-Phi-2-SigLIP-3.1B](https://huggingface.co/tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B)
141
+ - [TinyLLaVA-Gemma-SigLIP-2.4B](https://huggingface.co/tinyllava/TinyLLaVA-Gemma-SigLIP-2.4B)
142
+ - [TinyLLaVA-OpenELM-450M-SigLIP-0.89B](https://huggingface.co/jiajunlong/TinyLLaVA-0.89B)
143
+ - [TinyLLaVA-Qwen2-0.5B-SigLIP](https://huggingface.co/Zhang199/TinyLLaVA-Qwen2-0.5B-SigLIP)
144
+ - [TinyLLaVA-Qwen2.5-3B-SigLIP](https://huggingface.co/Zhang199/TinyLLaVA-Qwen2.5-3B-SigLIP)
145
+
146
+ #### Model Performance
147
+
148
+ | VT (HF Path) | LLM (HF Path) | Recipe | VQA-v2 | GQA | SQA-image | TextVQA | MM-Vet | POPE | MME | MMMU-val |
149
+ | --------------------------------- | ---------------------------------- | --------- | :----: | :--: | :-------: | :-----: | :----: | :--: | :----: | :------: |
150
+ | openai/clip-vit-large-patch14-336 | apple/OpenELM-450M-Instruct | base | 69.5 | 52.1 | 50.6 | 40.4 | 20.0 | 83.6 | 1052.9 | 23.9 |
151
+ | google/siglip-so400m-patch14-384 | apple/OpenELM-450M-Instruct | base | 71.7 | 53.9 | 54.1 | 44.0 | 20.0 | 85.4 | 1118.8 | 24.0 |
152
+ | google/siglip-so400m-patch14-384 | Qwen/Qwen2-0.5B | base | 72.3 | 55.8 | 60.1 | 45.2 | 19.5 | 86.6 | 1153.0 | 29.7 |
153
+ | google/siglip-so400m-patch14-384 | Qwen/Qwen2.5-0.5B | base | 75.3 | 59.5 | 60.3 | 48.3 | 23.9 | 86.1 | 1253.0 | 33.3 |
154
+ | google/siglip-so400m-patch14-384 | Qwen/Qwen2.5-3B | base | 79.4 | 62.5 | 74.1 | 58.3 | 34.8 | 87.4 | 1438.7 | 39.9 |
155
+ | openai/clip-vit-large-patch14-336 | TinyLlama/TinyLlama-1.1B-Chat-v1.0 | base | 73.7 | 58.0 | 59.9 | 46.3 | 23.2 | 85.5 | 1284.6 | 27.9 |
156
+ | google/siglip-so400m-patch14-384 | TinyLlama/TinyLlama-1.1B-Chat-v1.0 | base | 75.5 | 58.6 | 64.0 | 49.6 | 23.5 | 86.3 | 1256.5 | 28.3 |
157
+ | openai/clip-vit-large-patch14-336 | stabilityai/stablelm-2-zephyr-1_6b | base | 75.9 | 59.5 | 64.6 | 50.5 | 27.3 | 86.1 | 1368.1 | 31.8 |
158
+ | google/siglip-so400m-patch14-384 | stabilityai/stablelm-2-zephyr-1_6b | base | 78.2 | 60.7 | 66.7 | 56.0 | 29.4 | 86.3 | 1319.3 | 32.6 |
159
+ | google/siglip-so400m-patch14-384 | google/gemma-2b-it | base | 78.4 | 61.6 | 64.4 | 53.6 | 26.9 | 86.4 | 1339.0 | 31.7 |
160
+ | openai/clip-vit-large-patch14-336 | microsoft/phi-2 | base | 76.8 | 59.4 | 71.2 | 53.4 | 31.7 | 86.8 | 1448.6 | 36.3 |
161
+ | google/siglip-so400m-patch14-384 | microsoft/phi-2 | base | 79.2 | 61.6 | 71.9 | 57.4 | 35.0 | 87.2 | 1462.4 | 38.2 |
162
+ | google/siglip-so400m-patch14-384 | microsoft/phi-2 | base&lora | 77.6 | 59.7 | 71.6 | 53.8 | 33.3 | 87.9 | 1413.2 | 35.6 |
163
+ | google/siglip-so400m-patch14-384 | microsoft/phi-2 | share | 80.1 | 62.1 | 73.0 | 60.3 | 37.5 | 87.2 | 1466.4 | 38.4 |
164
+
165
+ ### Legacy Models
166
+
167
+ which are trained using the old codebase TinyLLaVABench.
168
+
169
+ - [TinyLLaVA-3.1B](https://huggingface.co/bczhou/TinyLLaVA-3.1B)
170
+ - [TinyLLaVA-2.0B](https://huggingface.co/bczhou/TinyLLaVA-2.0B)
171
+ - [TinyLLaVA-1.5B](https://huggingface.co/bczhou/TinyLLaVA-1.5B)
172
+ - [tiny-llava-hf](https://huggingface.co/bczhou/tiny-llava-v1-hf)
173
+
174
+ If you have models trained by our old codebase TinyLLaVABench and you still want to use them, we provide an example of [TinyLLaVA-3.1B](https://huggingface.co/bczhou/TinyLLaVA-3.1B) for how to use legacy models.
175
+
176
+ <details>
177
+ <summary>Example of using legacy models</summary>
178
+
179
+
180
+ ```Python
181
+ from tinyllava.eval.run_tiny_llava import eval_model
182
+ from tinyllava.model.convert_legecy_weights_to_tinyllavafactory import *
183
+
184
+ model = convert_legecy_weights_to_tinyllavafactory('bczhou/TinyLLaVA-3.1B')
185
+
186
+ prompt = "What are the things I should be cautious about when I visit here?"
187
+ image_file = "https://llava-vl.github.io/static/images/view.jpg"
188
+
189
+ args = type('Args', (), {
190
+ "model_path": None,
191
+ "model": model,
192
+ "query": prompt,
193
+ "conv_mode": "phi", # the same as conv_version in the training stage. Different LLMs have different conv_mode/conv_version, please replace it
194
+ "image_file": image_file,
195
+ "sep": ",",
196
+ "temperature": 0,
197
+ "top_p": None,
198
+ "num_beams": 1,
199
+ "max_new_tokens": 512
200
+ })()
201
+
202
+ eval_model(args)
203
+
204
+ """
205
+ Output:
206
+ When visiting this serene lakeside location with a wooden dock, there are a few things to be cautious about. First, ensure that the dock is stable and secure before stepping onto it, as it might be slippery or wet, especially if it's a wooden structure. Second, be mindful of the surrounding water, as it can be deep or have hidden obstacles, such as rocks or debris, that could pose a risk. Additionally, be aware of the weather conditions, as sudden changes in weather can make the area more dangerous. Lastly, respect the natural environment and wildlife, and avoid littering or disturbing the ecosystem.
207
+ """
208
+ ```
209
+
210
+ </details>
211
+
212
+
213
+
214
+ ## Launch Demo Locally
215
+
216
+ ### Gradio Web Demo
217
+ Launch a local web demo by running:
218
+ ```bash
219
+ python tinyllava/serve/app.py --model-path tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B
220
+ ```
221
+ ### CLI Inference
222
+ We also support running inference with CLI. To use our model, run:
223
+ ```bash
224
+ python -m tinyllava.serve.cli \
225
+ --model-path tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B \
226
+ --image-file "./tinyllava/serve/examples/extreme_ironing.jpg"
227
+ ```
228
+ ### Quick Inference Scripts
229
+ If you want to launch the model trained by yourself or us locally, here's an example.
230
+ <details>
231
+ <summary>Run inference with the model trained by yourself</summary>
232
+
233
+ ```Python
234
+ from tinyllava.eval.run_tiny_llava import eval_model
235
+
236
+ model_path = "/absolute/path/to/your/model/"
237
+ prompt = "What are the things I should be cautious about when I visit here?"
238
+ image_file = "https://llava-vl.github.io/static/images/view.jpg"
239
+ conv_mode = "phi" # or llama, gemma, etc
240
+
241
+ args = type('Args', (), {
242
+ "model_path": model_path,
243
+ "model": None,
244
+ "query": prompt,
245
+ "conv_mode": conv_mode,
246
+ "image_file": image_file,
247
+ "sep": ",",
248
+ "temperature": 0,
249
+ "top_p": None,
250
+ "num_beams": 1,
251
+ "max_new_tokens": 512
252
+ })()
253
+
254
+ eval_model(args)
255
+
256
+ """
257
+ Output:
258
+ XXXXXXXXXXXXXXXXX
259
+ """
260
+ ```
261
+ </details>
262
+
263
+ <details>
264
+ <summary>Run inference with the model trained by us using huggingface transformers</summary>
265
+
266
+ ```Python
267
+ from transformers import AutoTokenizer, AutoModelForCausalLM
268
+
269
+ hf_path = 'tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B'
270
+ model = AutoModelForCausalLM.from_pretrained(hf_path, trust_remote_code=True)
271
+ model.cuda()
272
+ config = model.config
273
+ tokenizer = AutoTokenizer.from_pretrained(hf_path, use_fast=False, model_max_length = config.tokenizer_model_max_length,padding_side = config.tokenizer_padding_side)
274
+ prompt="What are these?"
275
+ image_url="http://images.cocodataset.org/val2017/000000039769.jpg"
276
+ output_text, genertaion_time = model.chat(prompt=prompt, image=image_url, tokenizer=tokenizer)
277
+
278
+ print('model output:', output_text)
279
+ print('runing time:', genertaion_time)
280
+ ```
281
+ </details>
282
+
283
+ ## Custom Finetune
284
+ If you want to finetune TinyLLaVA with your custom datasets, please refer to [here](https://github.com/TinyLLaVA/TinyLLaVA_Factory/blob/main/CUSTOM_FINETUNE.md).
285
+
286
+ ## Customize Your Own Large Multimodel Models
287
+
288
+ ### LLM
289
+
290
+ If you want to add a new LLM by yourself, you need to create two files: one for chat template and the other for language model, under the folders `tinyllava/data/template/` and `tinyllava/model/llm/`.
291
+
292
+ Here is an example of adding the Gemma model.
293
+
294
+ Firstly, create `tinyllava/data/template/gemma_template.py`, which will be used for the finetuning stage.
295
+
296
+ ```python
297
+ from dataclasses import dataclass
298
+ from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union
299
+ from packaging import version
300
+
301
+ from .formatter import EmptyFormatter, StringFormatter
302
+ from .base import Template
303
+ from .formatter import Formatter
304
+ from . import register_template
305
+ from ...utils.constants import *
306
+
307
+ from transformers import PreTrainedTokenizer
308
+ import torch
309
+ import tokenizers
310
+
311
+
312
+ system = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions."
313
+
314
+ @register_template('gemma') # Enable the TemplateFactory to obtain the added template by this string ('gemma').
315
+ @dataclass
316
+ class GemmaTemplate(Template):
317
+ format_image_token: "Formatter" = StringFormatter(slot="<image>\n{{content}}")
318
+ format_user: "Formatter" = StringFormatter(slot="USER" + ": " + "{{content}}" + " ")
319
+ format_assistant: "Formatter" = StringFormatter(slot="ASSISTANT" + ": " + "{{content}}" + "<eos>") # to be modified according to the tokenizer you choose
320
+ system: "Formatter" = EmptyFormatter(slot=system+" ")
321
+ separator: "Formatter" = EmptyFormatter(slot=[' ASSISTANT: ', '<eos>']) # to be modified according to the tokenizer you choose
322
+
323
+ def _make_masks(self, labels, tokenizer, sep, eos_token_length, rounds):
324
+ # your code here
325
+ return labels, cur_len
326
+ ```
327
+ **Tips:**
328
+
329
+ Please ensure that the `labels` (returned by the `_make_masks` function) follows this format: answers and the eos token id are not masked, and the other tokens are masked with `-100`.
330
+
331
+ Secondly, create `tinyllava/model/llm/gemma.py`.
332
+
333
+ ```python
334
+ from transformers import GemmaForCausalLM, AutoTokenizer
335
+ # The LLM you want to add along with its corresponding tokenizer.
336
+
337
+ from . import register_llm
338
+
339
+ # Add GemmaForCausalLM along with its corresponding tokenizer and handle special tokens.
340
+ @register_llm('gemma') # Enable the LLMFactory to obtain the added LLM by this string ('gemma').
341
+ def return_gemmaclass():
342
+ def tokenizer_and_post_load(tokenizer):
343
+ tokenizer.pad_token = tokenizer.unk_token
344
+ return tokenizer
345
+ return (GemmaForCausalLM, (AutoTokenizer, tokenizer_and_post_load))
346
+ ```
347
+
348
+ Finally, create `scripts/train/train_gemma.sh` with the corresponding `LLM_VERSION` and `CONV_VERSION`.
349
+
350
+ ### Vision Tower
351
+
352
+ If you want to add a new vision tower, you need to implement a new vision tower class that should be inherited from the base class `VisionTower`. Here's an example of the MoF vision tower.
353
+
354
+ First, create `tinyllava/model/vision_tower/mof.py`
355
+
356
+ ```python
357
+ @register_vision_tower('mof')
358
+ class MoFVisionTower(VisionTower):
359
+ def __init__(self, cfg):
360
+ super().__init__(cfg)
361
+
362
+ self._vision_tower = MoF(cfg)
363
+ self._image_processor = # your image processor
364
+
365
+ def _load_model(self, vision_tower_name, **kwargs):
366
+ # your code here, make sure your model can be correctly loaded from pretrained parameters either by huggingface or pytorch loading
367
+
368
+ def forward(self, x, **kwargs):
369
+ # your code here
370
+ ```
371
+
372
+ Then, modify your training scripts with the corresponding `VT_VERSION`.
373
+
374
+ ### Connector
375
+
376
+ If you want to add a new connector, you need to implement a new connector class that should be inherited from the base class `Connector`. Here's an example of the Linear connector.
377
+
378
+ First, create `tinyllava/model/connector/linear.py`
379
+
380
+
381
+ ```python
382
+ import torch.nn as nn
383
+
384
+ from . import register_connector
385
+ from .base import Connector
386
+
387
+ @register_connector('linear') #Enable the ConnectorMFactory to obtain the added connector by this string ('linear').
388
+ class LinearConnector(Connector):
389
+ def __init__(self, config):
390
+ super().__init__()
391
+ self._connector = nn.Linear(config.vision_hidden_size, config.hidden_size) # define your connector model
392
+ ```
393
+
394
+ Then, modify your training scripts with the corresponding `CN_VERSION`.
395
+
396
+ ## Acknowledgement
397
+ We give special thanks to Lei Zhao, Luche Wang, Kaijun Luo, and Junchen Wang for building the [Demo](http://8843843nmph5.vicp.fun/#/).
398
+
399
+ ## Contact
400
+ If you have any questions, feel free to either initiate an *Issue* or contact us by WeChat (WeChatID: *TinyLLaVA*).
401
+
402
+ ## &#x270F; Citation
403
+
404
+ If you find our paper and code useful in your research, please consider giving a star :star: and citation :pencil:.
405
+
406
+ ```BibTeX
407
+ @misc{zhou2024tinyllava,
408
+ title={TinyLLaVA: A Framework of Small-scale Large Multimodal Models},
409
+ author={Baichuan Zhou and Ying Hu and Xi Weng and Junlong Jia and Jie Luo and Xien Liu and Ji Wu and Lei Huang},
410
+ year={2024},
411
+ eprint={2402.14289},
412
+ archivePrefix={arXiv},
413
+ primaryClass={cs.LG}
414
+ }
415
+ ```
416
+ ```BibTeX
417
+ @article{jia2024tinyllava,
418
+ title={TinyLLaVA Factory: A Modularized Codebase for Small-scale Large Multimodal Models},
419
+ author={Jia, Junlong and Hu, Ying and Weng, Xi and Shi, Yiming and Li, Miao and Zhang, Xingjian and Zhou, Baichuan and Liu, Ziyu and Luo, Jie and Huang, Lei and Wu, Ji},
420
+ journal={arXiv preprint arXiv:2405.11788},
421
+ year={2024}
422
+ }
423
+ ```
424
+
425
+
426
+ ## ❤️ Community efforts
427
+ * Our codebase is built upon the [LLaVA](https://github.com/haotian-liu/LLaVA) project. Great work!
428
+ * Our project uses data from the [ShareGPT4V](https://github.com/InternLM/InternLM-XComposer/tree/main/projects/ShareGPT4V) project. Great work!
TinyLLaVA_Factory/assets/architecture.jpg ADDED
TinyLLaVA_Factory/pyproject.toml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tinyllava"
7
+ version = "1.0.0"
8
+ description = "A Framework of Small-scale Large Multimodal Models."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "License :: OSI Approved :: Apache Software License",
14
+ ]
15
+ dependencies = [
16
+ "torch==2.0.1", "torchvision==0.15.2", "tiktoken", "openpyxl", "tensorboardX",
17
+ "transformers==4.40.1", "tokenizers==0.19.0", "sentencepiece==0.1.99", "shortuuid",
18
+ "accelerate==0.27.2", "bitsandbytes==0.41.0", "peft==0.10.0",
19
+ "pydantic<2,>=1", "markdown2[all]", "numpy==1.26.4", "scikit-learn==1.2.2",
20
+ "gradio==3.35.2", "gradio_client==0.2.9",
21
+ "requests", "httpx==0.24.0", "uvicorn", "fastapi",
22
+ "einops==0.6.1", "einops-exts==0.0.4", "timm==0.6.13",
23
+ "deepspeed==0.14.0", "ninja", "wandb",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ train = ["deepspeed==0.14.0", "ninja", "wandb"]
28
+
29
+ [project.urls]
30
+ "Homepage" = "https://github.com/DLCV-BUAA/TinyLLaVABench"
31
+ "Bug Tracker" = "https://github.com/DLCV-BUAA/TinyLLaVABench/issues"
32
+
33
+ [tool.setuptools.packages.find]
34
+ exclude = ["assets*", "benchmark*", "docs", "dist*", "playground*", "scripts*", "tests*"]
35
+
36
+ [tool.wheel]
37
+ exclude = ["assets*", "benchmark*", "docs", "dist*", "playground*", "scripts*", "tests*"]
38
+
TinyLLaVA_Factory/scripts/convert_answer_to_mmmu.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+
5
+
6
+ def eval_model(args):
7
+ answers = [json.loads(q) for q in open(os.path.expanduser(args.answers_file), "r")]
8
+ answers_dict = {}
9
+ for answer in answers:
10
+ answers_dict[answer["question_id"]] = answer["text"]
11
+ # print(answer)
12
+
13
+ with open(args.answers_output, "w") as f:
14
+ json.dump(answers_dict, f)
15
+
16
+
17
+ if __name__ == "__main__":
18
+ parser = argparse.ArgumentParser()
19
+ parser.add_argument(
20
+ "--answers-file",
21
+ type=str,
22
+ required=True
23
+ )
24
+ parser.add_argument(
25
+ "--answers-output",
26
+ type=str,
27
+ required=True
28
+ )
29
+ args = parser.parse_args()
30
+
31
+ eval_model(args)
TinyLLaVA_Factory/scripts/convert_gqa_for_eval.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("--src", type=str)
7
+ parser.add_argument("--dst", type=str)
8
+ args = parser.parse_args()
9
+
10
+ all_answers = []
11
+ for line_idx, line in enumerate(open(args.src)):
12
+ res = json.loads(line)
13
+ question_id = res['question_id']
14
+ text = res['text'].rstrip('.').lower()
15
+ all_answers.append({"questionId": question_id, "prediction": text})
16
+
17
+ with open(args.dst, 'w') as f:
18
+ json.dump(all_answers, f)
TinyLLaVA_Factory/scripts/convert_mmvet_for_eval.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("--src", type=str)
7
+ parser.add_argument("--dst", type=str)
8
+ args = parser.parse_args()
9
+
10
+ cur_result = {}
11
+
12
+ for line in open(args.src):
13
+ data = json.loads(line)
14
+ qid = data['question_id']
15
+ cur_result[f'v1_{qid}'] = data['text']
16
+
17
+ with open(args.dst, 'w') as f:
18
+ json.dump(cur_result, f, indent=2)
TinyLLaVA_Factory/scripts/convert_vqav2_for_submission.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import json
4
+
5
+ from tinyllava.eval.m4c_evaluator import EvalAIAnswerProcessor
6
+
7
+
8
+ def parse_args():
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument('--dir', type=str, default="./playground/data/eval/vqav2")
11
+ parser.add_argument('--ckpt', type=str, required=True)
12
+ parser.add_argument('--split', type=str, required=True)
13
+ return parser.parse_args()
14
+
15
+
16
+ if __name__ == '__main__':
17
+
18
+ args = parse_args()
19
+
20
+ src = os.path.join(args.dir, 'answers', args.split, args.ckpt, 'merge.jsonl')
21
+ test_split = os.path.join(args.dir, 'llava_vqav2_mscoco_test2015.jsonl')
22
+ dst = os.path.join(args.dir, 'answers_upload', args.split, f'{args.ckpt}.json')
23
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
24
+
25
+ results = []
26
+ error_line = 0
27
+ for line_idx, line in enumerate(open(src)):
28
+ try:
29
+ results.append(json.loads(line))
30
+ except:
31
+ error_line += 1
32
+
33
+ results = {x['question_id']: x['text'] for x in results}
34
+ test_split = [json.loads(line) for line in open(test_split)]
35
+ split_ids = set([x['question_id'] for x in test_split])
36
+
37
+ print(f'total results: {len(results)}, total split: {len(test_split)}, error_line: {error_line}')
38
+
39
+ all_answers = []
40
+
41
+ answer_processor = EvalAIAnswerProcessor()
42
+
43
+ for x in test_split:
44
+ if x['question_id'] not in results:
45
+ all_answers.append({
46
+ 'question_id': x['question_id'],
47
+ 'answer': ''
48
+ })
49
+ else:
50
+ all_answers.append({
51
+ 'question_id': x['question_id'],
52
+ 'answer': answer_processor(results[x['question_id']])
53
+ })
54
+
55
+ with open(dst, 'w') as f:
56
+ json.dump(all_answers, open(dst, 'w'))
TinyLLaVA_Factory/scripts/eval/gqa.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
4
+ IFS=',' read -ra GPULIST <<< "$gpu_list"
5
+
6
+ CHUNKS=${#GPULIST[@]}
7
+
8
+ SPLIT="llava_gqa_testdev_balanced"
9
+ GQADIR="/home/ai/data/llava/dataset/eval/gqa"
10
+
11
+ MODEL_PATH="/mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune/"
12
+ MODEL_NAME="tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune"
13
+ EVAL_DIR="/home/ai/data/llava/dataset/eval"
14
+
15
+ for IDX in $(seq 0 $((CHUNKS-1))); do
16
+ CUDA_VISIBLE_DEVICES=${GPULIST[$IDX]} python -m tinyllava.eval.model_vqa_loader \
17
+ --model-path $MODEL_PATH \
18
+ --question-file $EVAL_DIR/gqa/$SPLIT.jsonl \
19
+ --image-folder $EVAL_DIR/gqa/images \
20
+ --answers-file $EVAL_DIR/gqa/answers/$SPLIT/$MODEL_NAME/${CHUNKS}_${IDX}.jsonl \
21
+ --num-chunks $CHUNKS \
22
+ --chunk-idx $IDX \
23
+ --temperature 0 \
24
+ --conv-mode phi &
25
+ done
26
+
27
+ wait
28
+
29
+ output_file=$EVAL_DIR/gqa/answers/$SPLIT/$MODEL_NAME/merge.jsonl
30
+
31
+ # Clear out the output file if it exists.
32
+ > "$output_file"
33
+
34
+ # Loop through the indices and concatenate each file.
35
+ for IDX in $(seq 0 $((CHUNKS-1))); do
36
+ cat $EVAL_DIR/gqa/answers/$SPLIT/$MODEL_NAME/${CHUNKS}_${IDX}.jsonl >> "$output_file"
37
+ done
38
+
39
+ python scripts/convert_gqa_for_eval.py --src $output_file --dst $GQADIR/testdev_balanced_predictions.json
40
+
41
+ cd $GQADIR
42
+ python eval/eval.py --tier testdev_balanced
43
+
TinyLLaVA_Factory/scripts/eval/mme.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH="/home/jiajunlong/LLaVA/ying/checkpoints/tiny-llava-TinyLlama-1.1B-Chat-v1.0-clip-vit-large-patch14-336-tinyllama-llava-finetune"
4
+ MODEL_NAME="tiny-llava-TinyLlama-1.1B-Chat-v1.0-clip-vit-large-patch14-336-tinyllama-llava-finetune"
5
+ EVAL_DIR="/home/jiajunlong/llava_data/eval"
6
+
7
+ python -m tinyllava.eval.model_vqa_loader \
8
+ --model-path $MODEL_PATH \
9
+ --question-file $EVAL_DIR/MME/llava_mme.jsonl \
10
+ --image-folder $EVAL_DIR/MME/MME_Benchmark_release_version \
11
+ --answers-file $EVAL_DIR/MME/answers/$MODEL_NAME.jsonl \
12
+ --temperature 0 \
13
+ --conv-mode llama
14
+
15
+ cd $EVAL_DIR/MME
16
+
17
+ python convert_answer_to_mme.py --experiment $MODEL_NAME
18
+
19
+ cd eval_tool
20
+
21
+ python calculation.py --results_dir answers/$MODEL_NAME
22
+
TinyLLaVA_Factory/scripts/eval/mmmu.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH="/mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune-final"
4
+ MODEL_NAME="tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune-final"
5
+ EVAL_DIR="/home/ai/data/llava/dataset/eval"
6
+
7
+ python -m tinyllava.eval.model_vqa_mmmu \
8
+ --model-path $MODEL_PATH \
9
+ --question-file $EVAL_DIR/MMMU/anns_for_eval.json \
10
+ --image-folder $EVAL_DIR/MMMU/all_images \
11
+ --answers-file $EVAL_DIR/MMMU/answers/$MODEL_NAME.jsonl \
12
+ --temperature 0 \
13
+ --conv-mode phi
14
+
15
+ python scripts/convert_answer_to_mmmu.py \
16
+ --answers-file $EVAL_DIR/MMMU/answers/$MODEL_NAME.jsonl \
17
+ --answers-output $EVAL_DIR/MMMU/answers/"$MODEL_NAME"_output.json
18
+
19
+ cd $EVAL_DIR/MMMU/eval
20
+
21
+ python main_eval_only.py --output_path $EVAL_DIR/MMMU/answers/"$MODEL_NAME"_output.json
TinyLLaVA_Factory/scripts/eval/mmvet.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH="/mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-phi-2-clip-vit-large-patch14-336-baseline-finetune/"
4
+ MODEL_NAME="tiny-llava-phi-2-clip-vit-large-patch14-336-baseline-finetune2"
5
+ EVAL_DIR="/home/ai/data/llava/dataset/eval"
6
+
7
+ python -m tinyllava.eval.model_vqa \
8
+ --model-path $MODEL_PATH \
9
+ --question-file $EVAL_DIR/mm-vet/llava-mm-vet.jsonl \
10
+ --image-folder $EVAL_DIR/mm-vet/images \
11
+ --answers-file $EVAL_DIR/mm-vet/answers/$MODEL_NAME.jsonl \
12
+ --temperature 0 \
13
+ --conv-mode phi
14
+
15
+ mkdir -p $EVAL_DIR/mm-vet/results
16
+
17
+ python scripts/convert_mmvet_for_eval.py \
18
+ --src $EVAL_DIR/mm-vet/answers/$MODEL_NAME.jsonl \
19
+ --dst $EVAL_DIR/mm-vet/results/$MODEL_NAME.json
TinyLLaVA_Factory/scripts/eval/pope.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH="/mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-stablelm-2-zephyr-1_6b-siglip-so400m-patch14-384-base-finetune/"
4
+ MODEL_NAME="tiny-llava-stablelm-2-zephyr-1_6b-siglip-so400m-patch14-384-base-finetune"
5
+ EVAL_DIR="/home/ai/data/llava/dataset/eval"
6
+
7
+ python -m tinyllava.eval.model_vqa_pope \
8
+ --model-path $MODEL_PATH \
9
+ --question-file $EVAL_DIR/pope/llava_pope_test.jsonl \
10
+ --image-folder $EVAL_DIR/pope/val2014 \
11
+ --answers-file $EVAL_DIR/pope/answers/$MODEL_NAME.jsonl \
12
+ --temperature 0 \
13
+ --conv-mode phi
14
+
15
+ python tinyllava/eval/eval_pope.py \
16
+ --annotation-dir $EVAL_DIR/pope/coco \
17
+ --question-file $EVAL_DIR/pope/llava_pope_test.jsonl \
18
+ --result-file $EVAL_DIR/pope/answers/$MODEL_NAME.jsonl
TinyLLaVA_Factory/scripts/eval/sqa.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH="/mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune"
4
+ MODEL_NAME="tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune"
5
+ EVAL_DIR="/home/ai/data/llava/dataset/eval"
6
+ python -m tinyllava.eval.model_vqa_science \
7
+ --model-path $MODEL_PATH \
8
+ --question-file $EVAL_DIR/scienceqa/llava_test_CQM-A.json \
9
+ --image-folder $EVAL_DIR/scienceqa/images/test \
10
+ --answers-file $EVAL_DIR/scienceqa/answers/$MODEL_NAME.jsonl \
11
+ --single-pred-prompt \
12
+ --temperature 0 \
13
+ --conv-mode phi
14
+
15
+ python tinyllava/eval/eval_science_qa.py \
16
+ --base-dir $EVAL_DIR/scienceqa \
17
+ --result-file $EVAL_DIR/scienceqa/answers/$MODEL_NAME.jsonl \
18
+ --output-file $EVAL_DIR/scienceqa/answers/"$MODEL_NAME"_output.jsonl \
19
+ --output-result $EVAL_DIR/scienceqa/answers/"$MODEL_NAME"_result.json
20
+
TinyLLaVA_Factory/scripts/eval/textvqa.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH="/mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune/"
4
+ MODEL_NAME="tiny-llava-phi-2-siglip-so400m-patch14-384-base-finetune"
5
+ EVAL_DIR="/home/ai/data/llava/dataset/eval"
6
+
7
+ python -m tinyllava.eval.model_vqa_loader \
8
+ --model-path $MODEL_PATH \
9
+ --question-file $EVAL_DIR/textvqa/llava_textvqa_val_v051_ocr.jsonl \
10
+ --image-folder $EVAL_DIR/textvqa/train_images \
11
+ --answers-file $EVAL_DIR/textvqa/answers/$MODEL_NAME.jsonl \
12
+ --temperature 0 \
13
+ --conv-mode phi
14
+
15
+ python -m tinyllava.eval.eval_textvqa \
16
+ --annotation-file $EVAL_DIR/textvqa/TextVQA_0.5.1_val.json \
17
+ --result-file $EVAL_DIR/textvqa/answers/$MODEL_NAME.jsonl
18
+
TinyLLaVA_Factory/scripts/eval/vqav2.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
4
+ IFS=',' read -ra GPULIST <<< "$gpu_list"
5
+
6
+ CHUNKS=${#GPULIST[@]}
7
+
8
+ SPLIT="llava_vqav2_mscoco_test-dev2015"
9
+
10
+ MODEL_PATH="/mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-phi-2-clip-vit-large-patch14-336-baseline-finetune/"
11
+ MODEL_NAME="tiny-llava-phi-2-clip-vit-large-patch14-336-baseline-finetune2"
12
+ EVAL_DIR="/home/ai/data/llava/dataset/eval"
13
+
14
+ for IDX in $(seq 0 $((CHUNKS-1))); do
15
+ CUDA_VISIBLE_DEVICES=${GPULIST[$IDX]} python -m tinyllava.eval.model_vqa_loader \
16
+ --model-path $MODEL_PATH \
17
+ --question-file $EVAL_DIR/vqav2/$SPLIT.jsonl \
18
+ --image-folder $EVAL_DIR/vqav2/test2015 \
19
+ --answers-file $EVAL_DIR/vqav2/answers/$SPLIT/$MODEL_NAME/${CHUNKS}_${IDX}.jsonl \
20
+ --num-chunks $CHUNKS \
21
+ --chunk-idx $IDX \
22
+ --temperature 0 \
23
+ --conv-mode phi &
24
+ done
25
+
26
+ wait
27
+
28
+ output_file=$EVAL_DIR/vqav2/answers/$SPLIT/$MODEL_NAME/merge.jsonl
29
+
30
+ # Clear out the output file if it exists.
31
+ > "$output_file"
32
+
33
+ # Loop through the indices and concatenate each file.
34
+ for IDX in $(seq 0 $((CHUNKS-1))); do
35
+ cat $EVAL_DIR/vqav2/answers/$SPLIT/$MODEL_NAME/${CHUNKS}_${IDX}.jsonl >> "$output_file"
36
+ done
37
+
38
+ python scripts/convert_vqav2_for_submission.py --split $SPLIT --ckpt $MODEL_NAME --dir $EVAL_DIR/vqav2
TinyLLaVA_Factory/scripts/train/custom_finetune.sh ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH="/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json"
2
+ IMAGE_PATH="/home/ai/data/llava/dataset"
3
+ MODEL_MAX_LENGTH=3072
4
+ OUTPUT_DIR="/mnt/data/sata/yinghu/checkpoints/llava_factory/custom-finetune-TinyLLaVA-Phi-2-SigLIP-3.1B-lora"
5
+
6
+ deepspeed --include localhost:0,1,2,3 --master_port 29501 tinyllava/train/custom_finetune.py \
7
+ --deepspeed ./scripts/zero2.json \
8
+ --data_path $DATA_PATH \
9
+ --image_folder $IMAGE_PATH \
10
+ --is_multimodal True \
11
+ --conv_version phi \
12
+ --mm_vision_select_layer -2 \
13
+ --image_aspect_ratio square \
14
+ --fp16 True \
15
+ --training_recipe lora \
16
+ --tune_type_llm lora \
17
+ --tune_type_vision_tower frozen \
18
+ --tune_vision_tower_from_layer 0 \
19
+ --tune_type_connector full \
20
+ --lora_r 128 \
21
+ --lora_alpha 256 \
22
+ --group_by_modality_length False \
23
+ --pretrained_model_path "tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B" \
24
+ --output_dir $OUTPUT_DIR \
25
+ --num_train_epochs 1 \
26
+ --per_device_train_batch_size 4 \
27
+ --per_device_eval_batch_size 4 \
28
+ --gradient_accumulation_steps 8 \
29
+ --evaluation_strategy "no" \
30
+ --save_strategy "steps" \
31
+ --save_steps 50000 \
32
+ --save_total_limit 1 \
33
+ --learning_rate 1e-4 \
34
+ --weight_decay 0. \
35
+ --warmup_ratio 0.03 \
36
+ --lr_scheduler_type "cosine" \
37
+ --logging_steps 1 \
38
+ --tf32 False \
39
+ --model_max_length $MODEL_MAX_LENGTH \
40
+ --gradient_checkpointing True \
41
+ --dataloader_num_workers 8 \
42
+ --lazy_preprocess True \
43
+ --report_to tensorboard \
44
+ --tokenizer_use_fast False \
45
+ --run_name custom-finetune-TinyLLaVA-Phi-2-SigLIP-3.1B-lora
TinyLLaVA_Factory/scripts/train/finetune.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ if [ $# -ne 10 ]; then
3
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <CONV_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
4
+ exit 1
5
+ fi
6
+
7
+ # Assign the arguments to variables
8
+ DATA_PATH="$1"
9
+ IMAGE_PATH="$2"
10
+ LLM_VERSION="$3"
11
+ VT_VERSION="$4"
12
+ VT_VERSION2="$5"
13
+ CN_VERSION="$6"
14
+ CONV_VERSION="$7"
15
+ VERSION="$8"
16
+ TRAIN_RECIPE="$9"
17
+ MODEL_MAX_LENGTH="${10}"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH \
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version $CONV_VERSION \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm full \
38
+ --tune_type_vision_tower frozen\
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --group_by_modality_length True \
42
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
43
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune \
44
+ --num_train_epochs 1 \
45
+ --per_device_train_batch_size 8 \
46
+ --per_device_eval_batch_size 4 \
47
+ --gradient_accumulation_steps 4 \
48
+ --evaluation_strategy "no" \
49
+ --save_strategy "steps" \
50
+ --save_steps 50000 \
51
+ --save_total_limit 1 \
52
+ --learning_rate 2e-5 \
53
+ --weight_decay 0. \
54
+ --warmup_ratio 0.03 \
55
+ --lr_scheduler_type "cosine" \
56
+ --logging_steps 1 \
57
+ --tf32 False \
58
+ --model_max_length $MODEL_MAX_LENGTH \
59
+ --gradient_checkpointing True \
60
+ --dataloader_num_workers 8 \
61
+ --lazy_preprocess True \
62
+ --report_to tensorboard \
63
+ --tokenizer_use_fast False \
64
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune
TinyLLaVA_Factory/scripts/train/gemma/finetune_gemma.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ if [ $# -ne 10 ]; then
3
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <CONV_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
4
+ exit 1
5
+ fi
6
+
7
+ # Assign the arguments to variables
8
+ DATA_PATH="$1"
9
+ IMAGE_PATH="$2"
10
+ LLM_VERSION="$3"
11
+ VT_VERSION="$4"
12
+ VT_VERSION2="$5"
13
+ CN_VERSION="$6"
14
+ CONV_VERSION="$7"
15
+ VERSION="$8"
16
+ TRAIN_RECIPE="$9"
17
+ MODEL_MAX_LENGTH="${10}"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH \
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version $CONV_VERSION \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm full \
38
+ --tune_type_vision_tower frozen\
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --group_by_modality_length True \
42
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
43
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune \
44
+ --num_train_epochs 1 \
45
+ --per_device_train_batch_size 2 \
46
+ --per_device_eval_batch_size 4 \
47
+ --gradient_accumulation_steps 16 \
48
+ --evaluation_strategy "no" \
49
+ --save_strategy "steps" \
50
+ --save_steps 50000 \
51
+ --save_total_limit 1 \
52
+ --learning_rate 2e-5 \
53
+ --weight_decay 0. \
54
+ --warmup_ratio 0.03 \
55
+ --lr_scheduler_type "cosine" \
56
+ --logging_steps 1 \
57
+ --tf32 False \
58
+ --model_max_length $MODEL_MAX_LENGTH \
59
+ --gradient_checkpointing True \
60
+ --dataloader_num_workers 8 \
61
+ --lazy_preprocess True \
62
+ --report_to tensorboard \
63
+ --tokenizer_use_fast False \
64
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune
TinyLLaVA_Factory/scripts/train/gemma/pretrain_gemma.sh ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ if [ $# -ne 9 ]; then
4
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
5
+ exit 1
6
+ fi
7
+
8
+ # Assign the arguments to variables
9
+ DATA_PATH="$1"
10
+ IMAGE_PATH="$2"
11
+ LLM_VERSION="$3"
12
+ VT_VERSION="$4"
13
+ VT_VERSION2="$5"
14
+ CN_VERSION="$6"
15
+ VERSION="$7"
16
+ TRAIN_RECIPE="$8"
17
+ MODEL_MAX_LENGTH="$9"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH\
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version pretrain \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm frozen \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
42
+ --num_train_epochs 1 \
43
+ --per_device_train_batch_size 8 \
44
+ --per_device_eval_batch_size 4 \
45
+ --gradient_accumulation_steps 8 \
46
+ --evaluation_strategy "no" \
47
+ --save_strategy "steps" \
48
+ --save_steps 24000 \
49
+ --save_total_limit 1 \
50
+ --learning_rate 1e-3 \
51
+ --weight_decay 0. \
52
+ --warmup_ratio 0.03 \
53
+ --lr_scheduler_type "cosine" \
54
+ --logging_steps 1 \
55
+ --tf32 False \
56
+ --model_max_length $MODEL_MAX_LENGTH \
57
+ --gradient_checkpointing True \
58
+ --dataloader_num_workers 8 \
59
+ --lazy_preprocess True \
60
+ --report_to tensorboard \
61
+ --tokenizer_use_fast False \
62
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain
TinyLLaVA_Factory/scripts/train/gemma/train_gemma.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset
5
+
6
+ LLM_VERSION=google/gemma-2b-it
7
+ VT_VERSION=google/siglip-so400m-patch14-384
8
+ VT_VERSION2=""
9
+ CN_VERSION=mlp2x_gelu
10
+ CONV_VERSION=gemma
11
+ VERSION=base
12
+ TRAIN_RECIPE=common
13
+ MODEL_MAX_LENGTH=2048
14
+
15
+
16
+ bash scripts/train/gemma/pretrain_gemma.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/gemma/finetune_gemma.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/lora/finetune_lora.sh ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ if [ $# -ne 10 ]; then
3
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <CONV_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
4
+ exit 1
5
+ fi
6
+
7
+ # Assign the arguments to variables
8
+ DATA_PATH="$1"
9
+ IMAGE_PATH="$2"
10
+ LLM_VERSION="$3"
11
+ VT_VERSION="$4"
12
+ VT_VERSION2="$5"
13
+ CN_VERSION="$6"
14
+ CONV_VERSION="$7"
15
+ VERSION="$8"
16
+ TRAIN_RECIPE="$9"
17
+ MODEL_MAX_LENGTH="${10}"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:2,3,4,5 --master_port 29502 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero2.json \
24
+ --data_path $DATA_PATH \
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version $CONV_VERSION \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm lora \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --lora_r 128 \
42
+ --lora_alpha 256 \
43
+ --group_by_modality_length False \
44
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
45
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune \
46
+ --num_train_epochs 1 \
47
+ --per_device_train_batch_size 8 \
48
+ --per_device_eval_batch_size 4 \
49
+ --gradient_accumulation_steps 4 \
50
+ --evaluation_strategy "no" \
51
+ --save_strategy "steps" \
52
+ --save_steps 50000 \
53
+ --save_total_limit 1 \
54
+ --learning_rate 2e-4 \
55
+ --weight_decay 0. \
56
+ --warmup_ratio 0.03 \
57
+ --lr_scheduler_type "cosine" \
58
+ --logging_steps 1 \
59
+ --tf32 False \
60
+ --model_max_length $MODEL_MAX_LENGTH \
61
+ --gradient_checkpointing True \
62
+ --dataloader_num_workers 8 \
63
+ --lazy_preprocess True \
64
+ --report_to tensorboard \
65
+ --tokenizer_use_fast False \
66
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune
TinyLLaVA_Factory/scripts/train/lora/finetune_qlora.sh ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ if [ $# -ne 10 ]; then
3
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <CONV_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
4
+ exit 1
5
+ fi
6
+
7
+ # Assign the arguments to variables
8
+ DATA_PATH="$1"
9
+ IMAGE_PATH="$2"
10
+ LLM_VERSION="$3"
11
+ VT_VERSION="$4"
12
+ VT_VERSION2="$5"
13
+ CN_VERSION="$6"
14
+ CONV_VERSION="$7"
15
+ VERSION="$8"
16
+ TRAIN_RECIPE="$9"
17
+ MODEL_MAX_LENGTH="${10}"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:4,5,6,7 --master_port 29502 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero2.json \
24
+ --data_path $DATA_PATH \
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version $CONV_VERSION \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm qlora \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --lora_r 128 \
42
+ --lora_alpha 256 \
43
+ --group_by_modality_length False \
44
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
45
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune \
46
+ --num_train_epochs 1 \
47
+ --per_device_train_batch_size 8 \
48
+ --per_device_eval_batch_size 4 \
49
+ --gradient_accumulation_steps 4 \
50
+ --evaluation_strategy "no" \
51
+ --save_strategy "steps" \
52
+ --save_steps 50000 \
53
+ --save_total_limit 1 \
54
+ --learning_rate 2e-4 \
55
+ --weight_decay 0. \
56
+ --warmup_ratio 0.03 \
57
+ --lr_scheduler_type "cosine" \
58
+ --logging_steps 1 \
59
+ --tf32 False \
60
+ --model_max_length $MODEL_MAX_LENGTH \
61
+ --gradient_checkpointing True \
62
+ --dataloader_num_workers 8 \
63
+ --lazy_preprocess True \
64
+ --report_to tensorboard \
65
+ --tokenizer_use_fast False \
66
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune
TinyLLaVA_Factory/scripts/train/lora/train_phi_lora.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset
5
+
6
+ LLM_VERSION=microsoft/phi-2
7
+ VT_VERSION=google/siglip-so400m-patch14-384
8
+ VT_VERSION2=""
9
+ CN_VERSION=mlp2x_gelu
10
+ CONV_VERSION=phi
11
+ VERSION=base-lora-zero2-r128
12
+ PRETRAIN_TRAIN_RECIPE=common
13
+ FINETUNE_TRAIN_RECIPE=lora
14
+ MODEL_MAX_LENGTH=3072
15
+
16
+
17
+ bash scripts/train/pretrain.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$PRETRAIN_TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
18
+ bash scripts/train/lora/finetune_lora.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$FINETUNE_TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/lora/train_phi_qlora.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset
5
+
6
+ LLM_VERSION=microsoft/phi-2
7
+ VT_VERSION=google/siglip-so400m-patch14-384
8
+ VT_VERSION2=""
9
+ CN_VERSION=mlp2x_gelu
10
+ CONV_VERSION=phi
11
+ VERSION=base-qlora
12
+ PRETRAIN_TRAIN_RECIPE=common
13
+ FINETUNE_TRAIN_RECIPE=qlora_int8
14
+ MODEL_MAX_LENGTH=3072
15
+
16
+
17
+ bash scripts/train/pretrain.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$PRETRAIN_TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
18
+ bash scripts/train/lora/finetune_qlora.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$FINETUNE_TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/openelm/finetune_openelm.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ if [ $# -ne 10 ]; then
3
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <CONV_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
4
+ exit 1
5
+ fi
6
+
7
+ # Assign the arguments to variables
8
+ DATA_PATH="$1"
9
+ IMAGE_PATH="$2"
10
+ LLM_VERSION="$3"
11
+ VT_VERSION="$4"
12
+ VT_VERSION2="$5"
13
+ CN_VERSION="$6"
14
+ CONV_VERSION="$7"
15
+ VERSION="$8"
16
+ TRAIN_RECIPE="$9"
17
+ MODEL_MAX_LENGTH="${10}"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:2,3,4,5 --master_port 29503 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH \
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version $CONV_VERSION \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --fp16 True \
35
+ --tokenizer_name_or_path meta-llama/Llama-2-7b-hf \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm full \
38
+ --tune_type_vision_tower frozen\
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --group_by_modality_length True \
42
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
43
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune \
44
+ --num_train_epochs 1 \
45
+ --per_device_train_batch_size 16 \
46
+ --per_device_eval_batch_size 4 \
47
+ --gradient_accumulation_steps 2 \
48
+ --evaluation_strategy "no" \
49
+ --save_strategy "steps" \
50
+ --save_steps 50000 \
51
+ --save_total_limit 1 \
52
+ --learning_rate 2e-5 \
53
+ --weight_decay 0. \
54
+ --warmup_ratio 0.03 \
55
+ --lr_scheduler_type "cosine" \
56
+ --logging_steps 1 \
57
+ --tf32 False \
58
+ --model_max_length $MODEL_MAX_LENGTH \
59
+ --gradient_checkpointing True \
60
+ --dataloader_num_workers 8 \
61
+ --lazy_preprocess True \
62
+ --report_to tensorboard \
63
+ --tokenizer_use_fast False \
64
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune
TinyLLaVA_Factory/scripts/train/openelm/pretrain_openelm.sh ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ if [ $# -ne 9 ]; then
4
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
5
+ exit 1
6
+ fi
7
+
8
+ # Assign the arguments to variables
9
+ DATA_PATH="$1"
10
+ IMAGE_PATH="$2"
11
+ LLM_VERSION="$3"
12
+ VT_VERSION="$4"
13
+ VT_VERSION2="$5"
14
+ CN_VERSION="$6"
15
+ VERSION="$7"
16
+ TRAIN_RECIPE="$8"
17
+ MODEL_MAX_LENGTH="$9"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:0,1 --master_port 29503 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH\
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version pretrain \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --fp16 True \
35
+ --tokenizer_name_or_path meta-llama/Llama-2-7b-hf \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm frozen \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
42
+ --num_train_epochs 1 \
43
+ --per_device_train_batch_size 64 \
44
+ --per_device_eval_batch_size 4 \
45
+ --gradient_accumulation_steps 2 \
46
+ --evaluation_strategy "no" \
47
+ --save_strategy "steps" \
48
+ --save_steps 24000 \
49
+ --save_total_limit 1 \
50
+ --learning_rate 1e-3 \
51
+ --weight_decay 0. \
52
+ --warmup_ratio 0.03 \
53
+ --lr_scheduler_type "cosine" \
54
+ --logging_steps 1 \
55
+ --tf32 False \
56
+ --model_max_length $MODEL_MAX_LENGTH \
57
+ --gradient_checkpointing True \
58
+ --dataloader_num_workers 8 \
59
+ --lazy_preprocess True \
60
+ --report_to tensorboard \
61
+ --tokenizer_use_fast False \
62
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain
TinyLLaVA_Factory/scripts/train/openelm/train_openelm.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset
5
+
6
+ LLM_VERSION=apple/OpenELM-270M-Instruct
7
+ VT_VERSION=google/siglip-so400m-patch14-384
8
+ VT_VERSION2=""
9
+ CN_VERSION=mlp2x_gelu
10
+ CONV_VERSION=llama
11
+ VERSION=elm_base
12
+ TRAIN_RECIPE=common
13
+ MODEL_MAX_LENGTH=2048
14
+
15
+
16
+ bash scripts/train/openelm/pretrain_openelm.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/openelm/finetune_openelm.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/pretrain.sh ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ if [ $# -ne 9 ]; then
4
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
5
+ exit 1
6
+ fi
7
+
8
+ # Assign the arguments to variables
9
+ DATA_PATH="$1"
10
+ IMAGE_PATH="$2"
11
+ LLM_VERSION="$3"
12
+ VT_VERSION="$4"
13
+ VT_VERSION2="$5"
14
+ CN_VERSION="$6"
15
+ VERSION="$7"
16
+ TRAIN_RECIPE="$8"
17
+ MODEL_MAX_LENGTH="$9"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH\
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version pretrain \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm frozen \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
42
+ --num_train_epochs 1 \
43
+ --per_device_train_batch_size 32 \
44
+ --per_device_eval_batch_size 4 \
45
+ --gradient_accumulation_steps 2 \
46
+ --evaluation_strategy "no" \
47
+ --save_strategy "steps" \
48
+ --save_steps 24000 \
49
+ --save_total_limit 1 \
50
+ --learning_rate 1e-3 \
51
+ --weight_decay 0. \
52
+ --warmup_ratio 0.03 \
53
+ --lr_scheduler_type "cosine" \
54
+ --logging_steps 1 \
55
+ --tf32 False \
56
+ --model_max_length $MODEL_MAX_LENGTH \
57
+ --gradient_checkpointing True \
58
+ --dataloader_num_workers 8 \
59
+ --lazy_preprocess True \
60
+ --report_to tensorboard \
61
+ --tokenizer_use_fast False \
62
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain
TinyLLaVA_Factory/scripts/train/qwen2/finetune_qwen2.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ if [ $# -ne 10 ]; then
3
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <CONV_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
4
+ exit 1
5
+ fi
6
+
7
+ # Assign the arguments to variables
8
+ DATA_PATH="$1"
9
+ IMAGE_PATH="$2"
10
+ LLM_VERSION="$3"
11
+ VT_VERSION="$4"
12
+ VT_VERSION2="$5"
13
+ CN_VERSION="$6"
14
+ CONV_VERSION="$7"
15
+ VERSION="$8"
16
+ TRAIN_RECIPE="$9"
17
+ MODEL_MAX_LENGTH="${10}"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:0,1,2,3,4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH \
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version $CONV_VERSION \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --bf16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm full \
38
+ --tune_type_vision_tower frozen\
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --group_by_modality_length True \
42
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
43
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune \
44
+ --num_train_epochs 1 \
45
+ --per_device_train_batch_size 4 \
46
+ --per_device_eval_batch_size 4 \
47
+ --gradient_accumulation_steps 4 \
48
+ --evaluation_strategy "no" \
49
+ --save_strategy "steps" \
50
+ --save_steps 50000 \
51
+ --save_total_limit 1 \
52
+ --learning_rate 2e-5 \
53
+ --weight_decay 0. \
54
+ --warmup_ratio 0.03 \
55
+ --lr_scheduler_type "cosine" \
56
+ --logging_steps 1 \
57
+ --tf32 False \
58
+ --model_max_length $MODEL_MAX_LENGTH \
59
+ --gradient_checkpointing True \
60
+ --dataloader_num_workers 8 \
61
+ --lazy_preprocess True \
62
+ --report_to tensorboard \
63
+ --tokenizer_use_fast False \
64
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-finetune
TinyLLaVA_Factory/scripts/train/qwen2/pretrain_qwen2.sh ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ if [ $# -ne 9 ]; then
4
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
5
+ exit 1
6
+ fi
7
+
8
+ # Assign the arguments to variables
9
+ DATA_PATH="$1"
10
+ IMAGE_PATH="$2"
11
+ LLM_VERSION="$3"
12
+ VT_VERSION="$4"
13
+ VT_VERSION2="$5"
14
+ CN_VERSION="$6"
15
+ VERSION="$7"
16
+ TRAIN_RECIPE="$8"
17
+ MODEL_MAX_LENGTH="$9"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:0,1,2,3,4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH\
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version pretrain \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --bf16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm frozen \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
42
+ --num_train_epochs 1 \
43
+ --per_device_train_batch_size 16 \
44
+ --per_device_eval_batch_size 4 \
45
+ --gradient_accumulation_steps 2 \
46
+ --evaluation_strategy "no" \
47
+ --save_strategy "steps" \
48
+ --save_steps 24000 \
49
+ --save_total_limit 1 \
50
+ --learning_rate 1e-3 \
51
+ --weight_decay 0. \
52
+ --warmup_ratio 0.03 \
53
+ --lr_scheduler_type "cosine" \
54
+ --logging_steps 1 \
55
+ --tf32 False \
56
+ --model_max_length $MODEL_MAX_LENGTH \
57
+ --gradient_checkpointing True \
58
+ --dataloader_num_workers 8 \
59
+ --lazy_preprocess True \
60
+ --report_to tensorboard \
61
+ --tokenizer_use_fast False \
62
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain
TinyLLaVA_Factory/scripts/train/qwen2/readme.md ADDED
@@ -0,0 +1 @@
 
 
1
+ These codes work for Qwen/Qwen2-0.5B and Qwen/Qwen2-0.5B-Instruct. However there is bug causing from deepspeed when you use other Qwen2 models like qwen2-1.5B. If you want to use tinyllava to train other qwen2 models, please feel free to contact our team.
TinyLLaVA_Factory/scripts/train/qwen2/train_qwen2_base.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json #pretrain annotation file path
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json #finetune annotation file path
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images #pretrain image dir
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset #finetune image dir
5
+
6
+ LLM_VERSION=Qwen/Qwen2-0.5B # llm path in huggingface
7
+ VT_VERSION=google/siglip-so400m-patch14-384 #vision tower path in huggingface
8
+ VT_VERSION2="" #if you are not using mof vision tower, keep it empty
9
+ CN_VERSION=mlp2x_gelu #connector type, other options are: qformer, resampler, etc
10
+ CONV_VERSION=qwen2_base #chat template, other options are: phi, llama, gemmma, etc
11
+ VERSION=qwen2-0_5b_base #experiment name for recording different runnings
12
+ TRAIN_RECIPE=common #training recipes, other options are: lora, qlora
13
+ MODEL_MAX_LENGTH=2048 #max model length for llm
14
+
15
+
16
+ bash scripts/train/qwen2/pretrain_qwen2.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/qwen2/finetune_qwen2.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/qwen2/train_qwen2_instruct.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json #pretrain annotation file path
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json #finetune annotation file path
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images #pretrain image dir
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset #finetune image dir
5
+
6
+ LLM_VERSION=Qwen/Qwen2-0.5B-Instruct # llm path in huggingface
7
+ VT_VERSION=google/siglip-so400m-patch14-384 #vision tower path in huggingface
8
+ VT_VERSION2="" #if you are not using mof vision tower, keep it empty
9
+ CN_VERSION=mlp2x_gelu #connector type, other options are: qformer, resampler, etc
10
+ CONV_VERSION=qwen2_instruct #chat template, other options are: phi, llama, gemmma, etc
11
+ VERSION=qwen2-0_5b_instruct #experiment name for recording different runnings
12
+ TRAIN_RECIPE=common #training recipes, other options are: lora, qlora
13
+ MODEL_MAX_LENGTH=2048 #max model length for llm
14
+
15
+
16
+ bash scripts/train/qwen2/pretrain_qwen2.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/qwen2/finetune_qwen2.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/share/finetune_share.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ if [ $# -ne 10 ]; then
3
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <CONV_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
4
+ exit 1
5
+ fi
6
+
7
+ # Assign the arguments to variables
8
+ DATA_PATH="$1"
9
+ IMAGE_PATH="$2"
10
+ LLM_VERSION="$3"
11
+ VT_VERSION="$4"
12
+ VT_VERSION2="$5"
13
+ CN_VERSION="$6"
14
+ CONV_VERSION="$7"
15
+ VERSION="$8"
16
+ TRAIN_RECIPE="$9"
17
+ MODEL_MAX_LENGTH="${10}"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH \
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version $CONV_VERSION \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm full \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --group_by_modality_length True \
42
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-share-pretrain \
43
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-share-finetune \
44
+ --num_train_epochs 1 \
45
+ --per_device_train_batch_size 8 \
46
+ --per_device_eval_batch_size 4 \
47
+ --gradient_accumulation_steps 4 \
48
+ --evaluation_strategy "no" \
49
+ --save_strategy "steps" \
50
+ --save_steps 50000 \
51
+ --save_total_limit 1 \
52
+ --learning_rate 2e-5 \
53
+ --weight_decay 0. \
54
+ --warmup_ratio 0.03 \
55
+ --lr_scheduler_type "cosine" \
56
+ --logging_steps 1 \
57
+ --tf32 False \
58
+ --model_max_length $MODEL_MAX_LENGTH \
59
+ --gradient_checkpointing True \
60
+ --dataloader_num_workers 8 \
61
+ --lazy_preprocess True \
62
+ --report_to tensorboard \
63
+ --tokenizer_use_fast False \
64
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-share-finetune
TinyLLaVA_Factory/scripts/train/share/pretrain_share.sh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ if [ $# -ne 9 ]; then
4
+ echo "Usage: $0 <DATA_PATH> <IMAGE_PATH> <LLM_VERSION> <VT_VERSION> <VT_VERSION2> <CN_VERSION> <VERSION> <TRAIN_RECIPE> <MODEL_MAX_LENGTH>"
5
+ exit 1
6
+ fi
7
+
8
+ # Assign the arguments to variables
9
+ DATA_PATH="$1"
10
+ IMAGE_PATH="$2"
11
+ LLM_VERSION="$3"
12
+ VT_VERSION="$4"
13
+ VT_VERSION2="$5"
14
+ CN_VERSION="$6"
15
+ VERSION="$7"
16
+ TRAIN_RECIPE="$8"
17
+ MODEL_MAX_LENGTH="$9"
18
+
19
+ VT_VARIANT="${VT_VERSION#*/}"
20
+ LLM_VARIANT="${LLM_VERSION#*/}"
21
+
22
+ deepspeed --include localhost:4,5,6,7 --master_port 29501 tinyllava/train/train.py \
23
+ --deepspeed ./scripts/zero3.json \
24
+ --data_path $DATA_PATH\
25
+ --image_folder $IMAGE_PATH \
26
+ --is_multimodal True \
27
+ --conv_version pretrain \
28
+ --model_name_or_path $LLM_VERSION \
29
+ --vision_tower $VT_VERSION \
30
+ --vision_tower2 "$VT_VERSION2" \
31
+ --connector_type $CN_VERSION \
32
+ --mm_vision_select_layer -2 \
33
+ --image_aspect_ratio square \
34
+ --attn_implementation flash_attention_2 \
35
+ --fp16 True \
36
+ --training_recipe $TRAIN_RECIPE \
37
+ --tune_type_llm full \
38
+ --tune_type_vision_tower frozen \
39
+ --tune_vision_tower_from_layer 0 \
40
+ --tune_type_connector full \
41
+ --pretrained_model_path /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-pretrain \
42
+ --output_dir /mnt/data/sata/yinghu/checkpoints/llava_factory/tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-share-pretrain \
43
+ --num_train_epochs 1 \
44
+ --per_device_train_batch_size 8 \
45
+ --per_device_eval_batch_size 4 \
46
+ --gradient_accumulation_steps 8 \
47
+ --evaluation_strategy "no" \
48
+ --save_strategy "steps" \
49
+ --save_steps 24000 \
50
+ --save_total_limit 1 \
51
+ --learning_rate 2e-5 \
52
+ --weight_decay 0. \
53
+ --warmup_ratio 0.03 \
54
+ --lr_scheduler_type "cosine" \
55
+ --logging_steps 1 \
56
+ --tf32 False \
57
+ --model_max_length $MODEL_MAX_LENGTH \
58
+ --gradient_checkpointing True \
59
+ --dataloader_num_workers 8 \
60
+ --lazy_preprocess True \
61
+ --report_to tensorboard \
62
+ --tokenizer_use_fast False \
63
+ --run_name tiny-llava-${LLM_VARIANT}-${VT_VARIANT}-${VERSION}-share-pretrain
TinyLLaVA_Factory/scripts/train/share/train_phi_share.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json
2
+ SHARE_PRETRAIN_DATA_PATH=/mnt/data/sata/ssd/dataset/text_files/really_cleaned_share-captioner_coco_lcs_sam_1246k_1107.json
3
+ SHARE_FINETUNE_DATA_PATH=/mnt/data/sata/ssd/dataset/text_files/cleaned_sharegpt4v_mix665k_cap23k_coco-ap9k_lcs3k_sam9k_div2k.json
4
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images
5
+ SHARE_PRETRAIN_IMAGE_PATH=/home/ai/data/llava/dataset
6
+ SHARE_FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset
7
+
8
+ LLM_VERSION=microsoft/phi-2
9
+ VT_VERSION=google/siglip-so400m-patch14-384
10
+ VT_VERSION2=""
11
+ CN_VERSION=mlp2x_gelu
12
+ CONV_VERSION=phi
13
+ VERSION=share
14
+ TRAIN_RECIPE=common
15
+ MODEL_MAX_LENGTH=3072
16
+
17
+
18
+
19
+ bash scripts/train/pretrain.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
20
+ bash scripts/train/share/pretrain_share.sh "$SHARE_PRETRAIN_DATA_PATH" "$SHARE_PRETRAIN_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
21
+ bash scripts/train/share/finetune_share.sh "$SHARE_FINETUNE_DATA_PATH" "$SHARE_FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/train_mof.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset
5
+
6
+ LLM_VERSION=TinyLlama/TinyLlama-1.1B-Chat-v1.0
7
+ VT_VERSION=mof:openai/clip-vit-large-patch14
8
+ VT_VERSION2=mof:facebook/dinov2-large
9
+ CN_VERSION=mof_mlp
10
+ CONV_VERSION=llama
11
+ VERSION=llama-mof-base
12
+ TRAIN_RECIPE=common
13
+ MODEL_MAX_LENGTH=2048
14
+
15
+
16
+ bash scripts/train/pretrain.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/finetune.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/train_phi.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json #pretrain annotation file path
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json #finetune annotation file path
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images #pretrain image dir
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset #finetune image dir
5
+
6
+ LLM_VERSION=microsoft/phi-2 # llm path in huggingface
7
+ VT_VERSION=google/siglip-so400m-patch14-384 #vision tower path in huggingface
8
+ VT_VERSION2="" #if you are not using mof vision tower, keep it empty
9
+ CN_VERSION=mlp2x_gelu #connector type, other options are: qformer, resampler, etc
10
+ CONV_VERSION=phi #chat template, other options are: phi, llama, gemmma, etc
11
+ VERSION=base #experiment name for recording different runnings
12
+ TRAIN_RECIPE=common #training recipes, other options are: lora, qlora
13
+ MODEL_MAX_LENGTH=3072 #max model length for llm
14
+
15
+
16
+ bash scripts/train/pretrain.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/finetune.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/train_stablelm.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json #pretrain annotation file path
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json #finetune annotation file path
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images #pretrain image dir
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset #finetune image dir
5
+
6
+ LLM_VERSION=stabilityai/stablelm-2-zephyr-1_6b # llm path in huggingface
7
+ VT_VERSION=openai/clip-vit-large-patch14-336 #vision tower path in huggingface
8
+ VT_VERSION2="" #if you are not using mof vision tower, keep it empty
9
+ CN_VERSION=mlp2x_gelu #connector type, other options are: qformer, resampler, etc
10
+ CONV_VERSION=phi #chat template for stablelm is the same as that for phi
11
+ VERSION=base #experiment name for recording different runnings
12
+ TRAIN_RECIPE=common #training recipes, other options are: lora, qlora
13
+ MODEL_MAX_LENGTH=2048 #max model length for llm
14
+
15
+
16
+ bash scripts/train/pretrain.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/finetune.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/train/train_tinyllama.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA_PATH=/home/ai/data/llava/dataset/text_files/blip_laion_cc_sbu_558k.json #pretrain annotation file path
2
+ FINETUNE_DATA_PATH=/home/ai/data/llava/dataset/text_files/llava_v1_5_mix665k.json #finetune annotation file path
3
+ IMAGE_PATH=/home/ai/data/llava/dataset/llava/llava_pretrain/images #pretrain image dir
4
+ FINETUNE_IMAGE_PATH=/home/ai/data/llava/dataset #finetune image dir
5
+
6
+ LLM_VERSION=TinyLlama/TinyLlama-1.1B-Chat-v1.0 # llm path in huggingface
7
+ VT_VERSION=google/siglip-so400m-patch14-384 #vision tower path in huggingface
8
+ VT_VERSION2="" #if you are not using mof vision tower, keep it empty
9
+ CN_VERSION=mlp2x_gelu #connector type, other options are: qformer, resampler, etc
10
+ CONV_VERSION=llama #chat template, other options are: phi, llama, gemmma, etc
11
+ VERSION=base #experiment name for recording different runnings
12
+ TRAIN_RECIPE=common #training recipes, other options are: lora, qlora
13
+ MODEL_MAX_LENGTH=2048 #max model length for llm
14
+
15
+
16
+ bash scripts/train/pretrain.sh "$DATA_PATH" "$IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
17
+ bash scripts/train/finetune.sh "$FINETUNE_DATA_PATH" "$FINETUNE_IMAGE_PATH" "$LLM_VERSION" "$VT_VERSION" "$VT_VERSION2" "$CN_VERSION" "$CONV_VERSION" "$VERSION" "$TRAIN_RECIPE" "$MODEL_MAX_LENGTH"
TinyLLaVA_Factory/scripts/zero2.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 2,
18
+ "overlap_comm": true,
19
+ "contiguous_gradients": true,
20
+ "sub_group_size": 1e9,
21
+ "reduce_bucket_size": "auto"
22
+ }
23
+ }
TinyLLaVA_Factory/scripts/zero3.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 3,
18
+ "overlap_comm": true,
19
+ "contiguous_gradients": true,
20
+ "sub_group_size": 1e9,
21
+ "reduce_bucket_size": "auto",
22
+ "stage3_prefetch_bucket_size": "auto",
23
+ "stage3_param_persistence_threshold": "auto",
24
+ "stage3_max_live_parameters": 1e9,
25
+ "stage3_max_reuse_distance": 1e9,
26
+ "stage3_gather_16bit_weights_on_model_save": true
27
+ }
28
+ }
TinyLLaVA_Factory/tinyllava/__init__.py ADDED
File without changes
TinyLLaVA_Factory/tinyllava/data/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .template import *
2
+ from .image_preprocess import *
3
+ from .text_preprocess import *
4
+ from .dataset import *
TinyLLaVA_Factory/tinyllava/data/dataset.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from dataclasses import dataclass
3
+ import json
4
+ from typing import Dict, Sequence, TYPE_CHECKING
5
+ from PIL import Image, ImageFile
6
+ import os
7
+
8
+ from .text_preprocess import TextPreprocess
9
+ from .image_preprocess import ImagePreprocess
10
+ from ..utils.arguments import DataArguments
11
+ from ..utils.constants import *
12
+
13
+
14
+ import transformers
15
+ import torch
16
+ from torch.utils.data import Dataset
17
+
18
+
19
+
20
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
21
+
22
+ class LazySupervisedDataset(Dataset):
23
+ """Dataset for supervised fine-tuning."""
24
+
25
+ def __init__(self, data_path: str,
26
+ tokenizer: transformers.PreTrainedTokenizer,
27
+ data_args: DataArguments):
28
+ super(LazySupervisedDataset, self).__init__()
29
+ list_data_dict = json.load(open(data_path, "r"))
30
+
31
+ self.tokenizer = tokenizer
32
+ self.list_data_dict = list_data_dict
33
+ self.data_args = data_args
34
+ self.text_preprocess = TextPreprocess(tokenizer, data_args.conv_version)
35
+ self.image_preprocess = ImagePreprocess(data_args.image_processor, data_args)
36
+
37
+ def __len__(self):
38
+ return len(self.list_data_dict)
39
+
40
+ @property
41
+ def lengths(self):
42
+ length_list = []
43
+ for sample in self.list_data_dict:
44
+ img_tokens = 128 if 'image' in sample else 0
45
+ length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
46
+ return length_list
47
+
48
+ @property
49
+ def modality_lengths(self):
50
+ length_list = []
51
+ for sample in self.list_data_dict:
52
+ cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
53
+ cur_len = cur_len if 'image' in sample else -cur_len
54
+ length_list.append(cur_len)
55
+ return length_list
56
+
57
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
58
+ sources = self.list_data_dict[i]
59
+ data_dict = self.text_preprocess(copy.deepcopy(sources["conversations"]))
60
+ if 'image' in sources:
61
+ image_file = self.list_data_dict[i]['image']
62
+ image_folder = self.data_args.image_folder
63
+ image = Image.open(os.path.join(image_folder, image_file)).convert('RGB')
64
+ image = self.image_preprocess(image)
65
+ data_dict['image'] = image
66
+ elif self.data_args.is_multimodal:
67
+ # image does not exist in the data, but the model is multimodal
68
+ # print(f'{i}:{sources}')
69
+ crop_size = getattr(self.data_args.image_processor, 'crop_size', getattr(self.data_args.image_processor, 'size'))
70
+ data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width'])
71
+ return data_dict
72
+
73
+
74
+ @dataclass
75
+ class DataCollatorForSupervisedDataset(object):
76
+ """Collate examples for supervised fine-tuning."""
77
+
78
+ tokenizer: transformers.PreTrainedTokenizer
79
+
80
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
81
+ input_ids, labels = tuple([instance[key] for instance in instances]
82
+ for key in ("input_ids", "labels"))
83
+ if self.tokenizer.pad_token_id == self.tokenizer.eos_token_id:
84
+ for input_id in input_ids:
85
+ input_id[input_id == self.tokenizer.eos_token_id] = -300
86
+ input_ids = torch.nn.utils.rnn.pad_sequence(
87
+ input_ids,
88
+ batch_first=True,
89
+ padding_value=self.tokenizer.pad_token_id)
90
+ labels = torch.nn.utils.rnn.pad_sequence(labels,
91
+ batch_first=True,
92
+ padding_value=IGNORE_INDEX)
93
+ input_ids = input_ids[:, :self.tokenizer.model_max_length]
94
+ attention_mask = input_ids.ne(self.tokenizer.pad_token_id)
95
+ labels = labels[:, :self.tokenizer.model_max_length]
96
+ # FIXME: This is a hack for handling phi and stablelm, as they have the same eos, pad and unk. We want the model
97
+ # FIXME: to predict the eos in the input ids, but we also use the id of eos to pad sequence, so we use a temp
98
+ # FIXME: eos id first, and convert them back.
99
+ if self.tokenizer.pad_token_id == self.tokenizer.eos_token_id:
100
+ for input_id in input_ids:
101
+ input_id[input_id == -300] = self.tokenizer.eos_token_id
102
+
103
+ batch = dict(
104
+ input_ids=input_ids,
105
+ labels=labels,
106
+ attention_mask=attention_mask,
107
+ )
108
+
109
+ if 'image' in instances[0]:
110
+ images = [instance['image'] for instance in instances]
111
+ if all(x is not None and x.shape == images[0].shape for x in images):
112
+ batch['images'] = torch.stack(images)
113
+ else:
114
+ batch['images'] = images
115
+
116
+ return batch
117
+
118
+
119
+ def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
120
+ data_args) -> Dict:
121
+ """Make dataset and collator for supervised fine-tuning."""
122
+ train_dataset = LazySupervisedDataset(tokenizer=tokenizer,
123
+ data_path=data_args.data_path,
124
+ data_args=data_args)
125
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
126
+ return dict(train_dataset=train_dataset,
127
+ eval_dataset=None,
128
+ data_collator=data_collator)
TinyLLaVA_Factory/tinyllava/data/image_preprocess.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from PIL import Image, ImageFile
4
+ import torch
5
+ import ast
6
+
7
+ from ..utils.data_utils import *
8
+
9
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
10
+
11
+ # 可能imagepreprocess需要继承一个huggingface的图像处理类?提供from_pretrained方法
12
+
13
+ class ImagePreprocess:
14
+ def __init__(self, image_processor, data_args={}):
15
+ self.image_aspect_ratio = getattr(data_args, 'image_aspect_ratio', None)
16
+ self.image_processor = image_processor
17
+ self.image_grid_pinpoints = getattr(data_args, 'image_grid_pinpoints', None)
18
+
19
+ def __call__(self, image):
20
+ if self.image_aspect_ratio == 'pad':
21
+ image = self.expand2square(image, tuple(int(x * 255) for x in self.image_processor.image_mean))
22
+ elif self.image_aspect_ratio == "anyres":
23
+ image = self.process_anyres_image(image, self.image_processor, self.image_grid_pinpoints)
24
+ return image
25
+ image = self.image_processor(image, return_tensors='pt')['pixel_values'][0]
26
+ return image
27
+
28
+ @classmethod
29
+ def expand2square(cls, pil_img, background_color):
30
+ width, height = pil_img.size
31
+ if width == height:
32
+ return pil_img
33
+ elif width > height:
34
+ result = Image.new(pil_img.mode, (width, width), background_color)
35
+ result.paste(pil_img, (0, (width - height) // 2))
36
+ return result
37
+ else:
38
+ result = Image.new(pil_img.mode, (height, height), background_color)
39
+ result.paste(pil_img, ((height - width) // 2, 0))
40
+ return result
41
+
42
+ @classmethod
43
+ def process_anyres_image(cls, image, processor, grid_pinpoints):
44
+ """
45
+ Process an image with variable resolutions.
46
+
47
+ Args:
48
+ image (PIL.Image.Image): The input image to be processed.
49
+ processor: The image processor object.
50
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
51
+
52
+ Returns:
53
+ torch.Tensor: A tensor containing the processed image patches.
54
+ """
55
+ if type(grid_pinpoints) is list:
56
+ possible_resolutions = grid_pinpoints
57
+ else:
58
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
59
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
60
+ image_padded = resize_and_pad_image(image, best_resolution)
61
+
62
+ patches = divide_to_patches(image_padded, processor.crop_size['height'])
63
+
64
+ image_original_resize = image.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
65
+
66
+ image_patches = [image_original_resize] + patches
67
+ image_patches = [processor(image_patch, return_tensors='pt')['pixel_values'][0]
68
+ for image_patch in image_patches]
69
+ return torch.stack(image_patches, dim=0)
70
+
TinyLLaVA_Factory/tinyllava/data/template/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Dict
3
+
4
+ from .base import *
5
+ from ...utils import import_modules
6
+
7
+
8
+ TEMPlATE_FACTORY: Dict[str, Template] = {}
9
+
10
+ def TemplateFactory(version):
11
+ template = TEMPlATE_FACTORY.get(version, None)
12
+ assert template, f"{version} is not implmentation"
13
+ return template
14
+
15
+
16
+ def register_template(name):
17
+ def register_template_cls(cls):
18
+ if name in TEMPlATE_FACTORY:
19
+ return TEMPlATE_FACTORY[name]
20
+
21
+ TEMPlATE_FACTORY[name] = cls
22
+ return cls
23
+
24
+ return register_template_cls
25
+
26
+
27
+ # automatically import any Python files in the models/ directory
28
+ models_dir = os.path.dirname(__file__)
29
+ import_modules(models_dir, "tinyllava.data.template")