aipib commited on
Commit
01ce7fd
·
verified ·
1 Parent(s): 72a72f3

Upload 13 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ asagi-1.9B-F16.gguf filter=lfs diff=lfs merge=lfs -text
37
+ mmproj-model-f16.gguf filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,210 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - ja
5
+ base_model:
6
+ - llm-jp/llm-jp-3-1.8b-instruct
7
+ pipeline_tag: image-text-to-text
8
+ library_name: transformers
9
+ tags:
10
+ - llava
11
+ ---
12
+
13
+ ## Model Details
14
+
15
+ ### Model Description
16
+
17
+ This repository provides Asagi-2B, a large-scale Japanese Vision & Language Model (VLM).
18
+ Asagi-2B has been trained on an extensive Japanese dataset, incorporating a diverse range of data sources.
19
+
20
+ A significant portion of the training data is synthesized using models such as the Japanese large language model ([CALM3-22B-Chat](https://huggingface.co/cyberagent/calm3-22b-chat)) and the English Vision & Language Model ([Phi3.5-vision-instruct](https://huggingface.co/microsoft/Phi-3.5-vision-instruct)).
21
+
22
+ Importantly, we do not use LLMs that restrict the usage of their outputs in the license terms (e.g., GPT-4) to synthesize the training data.
23
+
24
+
25
+ |Model components|Model / Architecture|Parameters|
26
+ |:---:|:---:|:---:|
27
+ |Vision encoder|[siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384)|428M|
28
+ |Projector|2-layer MLP|64M|
29
+ |LLM|[llm-jp-3-1.8b-instruct](https://huggingface.co/llm-jp/llm-jp-3-1.8b-instruct)|1.8B|
30
+
31
+
32
+ ## Usage
33
+
34
+ ### Requirements
35
+
36
+ ```txt
37
+ transformers==4.45.1
38
+ accelerate==0.34.2
39
+ torch==2.4.0
40
+ torchvision==0.19.0
41
+ ```
42
+
43
+ ### How to use
44
+ ```python
45
+ import requests
46
+ import torch
47
+ import transformers
48
+ from PIL import Image
49
+ from transformers import AutoModel, AutoProcessor, GenerationConfig
50
+
51
+ transformers.set_seed(42)
52
+ model_path = "MIL-UT/Asagi-2B"
53
+ processor = AutoProcessor.from_pretrained(model_path)
54
+ model = AutoModel.from_pretrained(
55
+ model_path, trust_remote_code=True,
56
+ torch_dtype=torch.bfloat16,
57
+ device_map="auto"
58
+ )
59
+
60
+ generation_config = GenerationConfig(
61
+ do_sample=True,
62
+ num_beams=5,
63
+ max_new_tokens=256,
64
+ temperature=0.7,
65
+ repetition_penalty=1.5
66
+ )
67
+
68
+ prompt = ("以下は、タスクを説明する指示です。要求を適切に満たす応答を書きなさい。\n\n"
69
+ "### 指示:\n<image>\nこの画像を見て、次の質問に詳細かつ具体的に答えてください。この写真はどこで撮影されたものか教えてください。また、画像の内容についても詳しく説明してください。\n\n### 応答:\n")
70
+
71
+ # sample image
72
+ sample_image_url = "https://raw.githubusercontent.com/uehara-mech/uehara-mech.github.io/refs/heads/master/images/shibuya.jpg"
73
+ image = Image.open(requests.get(sample_image_url, stream=True).raw)
74
+
75
+ inputs = processor(
76
+ text=prompt, images=image, return_tensors="pt"
77
+ )
78
+ inputs_text = processor.tokenizer(prompt, return_tensors="pt")
79
+ inputs['input_ids'] = inputs_text['input_ids']
80
+ inputs['attention_mask'] = inputs_text['attention_mask']
81
+ for k, v in inputs.items():
82
+ if v.dtype == torch.float32:
83
+ inputs[k] = v.to(model.dtype)
84
+ inputs = {k: inputs[k].to(model.device) for k in inputs if k != "token_type_ids"}
85
+
86
+ generate_ids = model.generate(
87
+ **inputs,
88
+ generation_config=generation_config
89
+ )
90
+ generated_text = processor.batch_decode(
91
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
92
+ )[0]
93
+
94
+ # do not print the prompt
95
+ if "<image>" in prompt:
96
+ prompt = prompt.replace("<image>", " ")
97
+ generated_text = generated_text.replace(prompt, "")
98
+
99
+ print(f"Generated text: {generated_text}")
100
+
101
+ # >>> Generated text: この写真は渋谷の交差点で撮影されたものです。写真には、夜の渋谷の街並みが写っており、多くの高層ビルが立ち並んでいます。特に目を引くのは、中央に位置する大きな白いビルで、その周囲には小さなビルが立ち並んでいます。ビルの窓からは街の明かりが漏れ、街全体が活気に満ちている様子が伝わってきます。
102
+
103
+ ```
104
+
105
+ ### Example
106
+ <img src="https://raw.githubusercontent.com/uehara-mech/uehara-mech.github.io/refs/heads/master/images/shibuya.jpg" width="350">
107
+
108
+ | Prompt | Output |
109
+ |:---|:---|
110
+ | この画像を見て、次の質問に詳細かつ具体的に答えてください。この写真はどこで撮影されたものか教えてください。また、画像の内容についても詳しく説明してください。 |この写真は渋谷の交差点で撮影されたものです。写真には、夜の渋谷の街並みが写っており、多くの高層ビルが立ち並んでいます。特に目を引くのは、中央に位置する大きな白いビルで、その周囲には小さなビルが立ち並んでいます。ビルの窓からは街の明かりが漏れ、街全体が活気に満ちている様子が伝わってきます。|
111
+
112
+
113
+ ### More Examples
114
+ <details>
115
+ <summary>Click to expand</summary>
116
+ <img src="https://raw.githubusercontent.com/uehara-mech/uehara-mech.github.io/refs/heads/master/images/bridge.jpg" width="300">
117
+
118
+ | Prompt | Output |
119
+ |:---|:---|
120
+ | この画像を見て、次の指示に詳細かつ具体的に答えてください。この写真の内容について詳しく教えてく��さい。 |この写真は、東京のレインボーブリッジを撮影したものです。橋は白く塗装されており、水の上に架かっています。背景には高層ビルが立ち並ぶ都市景観が広がっており、空は澄み切った青色で、白い雲が浮かんでいます。|
121
+
122
+ <img src="https://raw.githubusercontent.com/uehara-mech/uehara-mech.github.io/refs/heads/master/images/tower.jpg" width="300">
123
+
124
+ | Prompt | Output |
125
+ |:---|:---|
126
+ | この画像を見て、次の質問に詳細かつ具体的に答えてください。この写真について評価してください。 |この写真は非常に低い解像度と品質のため、詳細な説明が困難です。|
127
+
128
+ <img src="https://raw.githubusercontent.com/uehara-mech/uehara-mech.github.io/refs/heads/master/images/shrine.jpg" width="300">
129
+
130
+ | Prompt | Output |
131
+ |:---|:---|
132
+ | この画像を見て、次の質問に詳細かつ具体的に答えてください。この写真の神社について、細かいところまで詳しく説明してください。 |この写真の神社は、日本の伝統的な神社建築様式を反映しています。白い壁と赤い屋根のコントラストが美しく、神聖な雰囲気を醸し出しています。入り口には朱塗りの鳥居が立ち、神聖な空間への入り口を象徴しています。また、神社の前には石畳の道が続いており、参拝者を神聖な場所へと導いています。|
133
+
134
+
135
+ <img src="https://raw.githubusercontent.com/uehara-mech/uehara-mech.github.io/refs/heads/master/images/garden.jpg" width="300">
136
+
137
+ | Prompt | Output |
138
+ |:---|:---|
139
+ | この画像を見て、次の指示に詳細かつ具体的に答えてください。これは日本庭園の中でも、どのような形式に分類される庭園ですか?また、その理由は何ですか? |この日本庭園は、伝統的な日本庭園の形式に基づいており、自然との調和を重視した設計が特徴です。池や岩、石灯籠などが配置され、静かで落ち着いた雰囲気を醸し出しています。このような庭園は、日本の伝統的な美意識である「わびさび」を体現しており、自然と人間の調和を大切にする精神を体現しています。|
140
+
141
+ <img src="https://raw.githubusercontent.com/uehara-mech/uehara-mech.github.io/refs/heads/master/images/slope.jpg" width="200">
142
+
143
+ | Prompt | Output |
144
+ |:---|:---|
145
+ | この画像を見て、次の質問に詳細に答えてください。この画像の場所を舞台とした小説のあらすじを書いてください。 |この画像の場所を舞台にした小説は、日本の伝統的な街並みを舞台にしています。石畳の道を進むと、古い木造建築が立ち並び、歴史を感じさせる風景が広がっています。石畳の道沿いには、緑豊かな植物が生い茂り、自然との調和を大切にする日本の美意識が感じられます。この物語は、都会の喧騒を離れ、自然と一体になれるような、静かで穏やかな雰囲気を醸し出しています。|
146
+
147
+ </details>
148
+
149
+
150
+ ## Training Details
151
+
152
+ ### Training Data
153
+
154
+ | Dataset | Preprocess | Stage1 | Stage2 | Size |
155
+ |:--------------------------|:-------------:|:-------:|:------:|:---------:|
156
+ | ROIS (Ours) | Synthesized | ✓ | ✓ | 8.4M |
157
+ | Japanese image text pairs | Synthesized | ✓ | ✓ | 4.4M |
158
+ | Wikipedia | Synthesized | ✓ | ✓ | 2.5M |
159
+ | Open Images | Translated | ✓ | ✓ | 680K |
160
+ | DCI | Translated | ✓ | ✓ | 7K |
161
+ | CommonCatalog CC-BY | Translated | ✓ | ✓ | 3.5M |
162
+ | LLaVA-Pretrain-JA | | ✓ | ✓ | 550K |
163
+ | STAIR Captions | | ✓ | ✓ | 410K |
164
+ | Flickr-JP | | ✓ | ✓ | 160K |
165
+ | YJ Captions | | ✓ | ✓ | 130K |
166
+ | Japanese Pascal | | ✓ | ✓ | 5K |
167
+ | ArtBench | Synthesized | | ✓ | 100K |
168
+ | GQA | Translated | | ✓ | 1.9M |
169
+ | VQA v2 | Translated | | ✓ | 880K |
170
+ | A-OKVQA | Translated | | ✓ | 34K |
171
+ | OK-VQA | Translated | | ✓ | 18K |
172
+ | Japanese Visual Genome | Translated | | ✓ | 1.6M |
173
+ | PangeaInstruct | | | ✓ | 93K |
174
+
175
+ Note: ROIS (Ours) is a newly collected dataset crawled from the web specifically for this project.
176
+ The dataset consists of image and raw text pairs, which are used to synthesize the training data.
177
+
178
+ ## Evaluation
179
+
180
+ We evaluated our model using Heron-Bench, JA-VLM-Bench-in-the-Wild, and JA-VG-VQA-500.
181
+ We used eval-mm library for this evaluation.
182
+
183
+ Here, models with "†" are not trained with GPT-generated data.
184
+ Bold numbers indicate the best performance among all models, and underlined numbers indicate the best performance among models not trained with GPT-generated data.
185
+
186
+
187
+ | Model | LM Size | Heron-Bench (LLM (%)) | JA-VLM-Bench-In-the-Wild (ROUGE-L) | JA-VLM-Bench-In-the-Wild (LLM (/5.0)) | JA-VG-VQA-500 (ROUGE-L) | JA-VG-VQA-500 (LLM (/5.0)) |
188
+ |:-------------------------------|:--------:|:--------------------:|:---------------------------------:|:-----------------------------------:|:---------------------:|:-----------------------:|
189
+ | Japanese InstructBLIP Alpha† | 7B | 14.0 | 20.8 | 2.42 | - | - |
190
+ | Japanese Stable VLM† | 7B | 24.2 | 23.3 | 2.47 | - | - |
191
+ | LLaVA-CALM2-SigLIP† | 7B | 43.3 | 47.2 | 3.15 | 17.4 | 3.21 |
192
+ | Llama-3-EvoVLM-JP-v2 | 8B | 39.3 | 41.4 | 2.92 | 23.5 | 2.96 |
193
+ | VILA-jp | 13B |**57.2**|**52.3**| **3.69**| 16.2 | 3.62 |
194
+ | Asagi-2B† | 1.8B | 44.7 | 48.8 | 3.26 | 53.7 | 3.69 |
195
+ | Asagi-4B† | 3.7B | 49.3 | 49.6 | 3.38 | 55.6 | 3.78 |
196
+ | Asagi-8B† | 7.2B | 54.7 | 49.4 | <u>3.45</u> | 56.43 | <u>**3.84**</u> |
197
+ | Asagi-14B† | 13B | <u>55.8</u> | <u>50.8</u> | 3.44 | <u>**56.8**</u> | <u>**3.84**</u> |
198
+ | GPT-4o | - | 87.6 | 37.6 | 3.85 | 12.1 | 3.58 |
199
+
200
+
201
+
202
+
203
+ ## Risks and Limitations
204
+
205
+ The models released here are in the early stages of our research and development and have not been tuned to ensure outputs align with human intent and safety considerations.
206
+
207
+
208
+ ## Model Card Authors
209
+
210
+ Kohei Uehara
asagi-1.9B-F16.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b670be977d4440ff7c609687a20f4fcf3547bb347bc70451a17a87e66d678425
3
+ size 3737817472
config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "",
3
+ "architectures": [
4
+ "LlavaForConditionalGeneration"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_llava.LlavaConfig",
8
+ "AutoModel": "modeling_llava.LlavaForConditionalGeneration"
9
+ },
10
+ "ignore_index": -100,
11
+ "image_seq_length": 576,
12
+ "image_token_index": 99574,
13
+ "model_type": "llava",
14
+ "pad_token_id": 99575,
15
+ "projector_hidden_act": "gelu",
16
+ "projector_hidden_size": 4096,
17
+ "text_config": {
18
+ "_name_or_path": "llm-jp/llm-jp-3-1.8b-instruct",
19
+ "architectures": [
20
+ "LlamaForCausalLM"
21
+ ],
22
+ "hidden_size": 2048,
23
+ "intermediate_size": 7168,
24
+ "max_position_embeddings": 4096,
25
+ "model_type": "llama",
26
+ "num_attention_heads": 16,
27
+ "num_hidden_layers": 24,
28
+ "num_key_value_heads": 16,
29
+ "rms_norm_eps": 1e-05,
30
+ "torch_dtype": "bfloat16",
31
+ "vocab_size": 99584
32
+ },
33
+ "tie_word_embeddings": false,
34
+ "torch_dtype": "bfloat16",
35
+ "transformers_version": "4.45.2",
36
+ "vision_config": {
37
+ "hidden_act": "gelu_pytorch_tanh",
38
+ "hidden_size": 1152,
39
+ "image_size": 384,
40
+ "intermediate_size": 4304,
41
+ "layer_norm_eps": 1e-06,
42
+ "model_type": "siglip_vision_model",
43
+ "num_attention_heads": 16,
44
+ "num_hidden_layers": 27,
45
+ "patch_size": 14,
46
+ "projection_dim": 768,
47
+ "vocab_size": 99584
48
+ },
49
+ "vision_feature_layer": -2,
50
+ "vision_feature_select_strategy": "default",
51
+ "vocab_size": 99584
52
+ }
configuration_llava.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team.
3
+ # All rights reserved.
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Llava model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.models.auto import CONFIG_MAPPING
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class LlavaConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`LlavaForConditionalGeneration`].
27
+ It is used to instantiate an
28
+ Llava model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the Llava-9B.
30
+
31
+ e.g. [llava-hf/llava-9b](https://huggingface.co/llava-hf/llava-9b)
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+ Args:
37
+ vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
38
+ The config object or dictionary of the vision backbone.
39
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
40
+ The config object or dictionary of the text backbone.
41
+ ignore_index (`int`, *optional*, defaults to -100):
42
+ The ignore index for the loss function.
43
+ image_token_index (`int`, *optional*, defaults to 32000):
44
+ The image token index to encode the image prompt.
45
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
46
+ The activation function used by the multimodal projector.
47
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
48
+ The feature selection strategy used to select the vision feature from the vision backbone.
49
+ Can be one of `"default"` or `"full"`.
50
+ vision_feature_layer (`int`, *optional*, defaults to -2):
51
+ The index of the layer to select the vision feature.
52
+
53
+ Example:
54
+
55
+ ```python
56
+ >>> from transformers import LlavaForConditionalGeneration, LlavaConfig, CLIPVisionConfig, LlamaConfig
57
+
58
+ >>> # Initializing a CLIP-vision config
59
+ >>> vision_config = CLIPVisionConfig()
60
+
61
+ >>> # Initializing a Llama config
62
+ >>> text_config = LlamaConfig()
63
+
64
+ >>> # Initializing a Llava llava-1.5-7b style configuration
65
+ >>> configuration = LlavaConfig(vision_config, text_config)
66
+
67
+ >>> # Initializing a model from the llava-1.5-7b style configuration
68
+ >>> model = LlavaForConditionalGeneration(configuration)
69
+
70
+ >>> # Accessing the model configuration
71
+ >>> configuration = model.config
72
+ ```"""
73
+
74
+ model_type = "llava"
75
+ is_composition = False
76
+
77
+ def __init__(
78
+ self,
79
+ vision_config=None,
80
+ text_config=None,
81
+ ignore_index=-100,
82
+ image_token_index=32000,
83
+ projector_hidden_act="gelu",
84
+ vision_feature_select_strategy="default",
85
+ vision_feature_layer=-2,
86
+ projector_hidden_size=None,
87
+ **kwargs,
88
+ ):
89
+ self.ignore_index = ignore_index
90
+ self.image_token_index = image_token_index
91
+ self.projector_hidden_act = projector_hidden_act
92
+
93
+ if vision_feature_select_strategy not in ["default", "full"]:
94
+ raise ValueError(
95
+ "vision_feature_select_strategy should be one of 'default', 'full'."
96
+ f"Got: {vision_feature_select_strategy}"
97
+ )
98
+
99
+ self.vision_feature_select_strategy = vision_feature_select_strategy
100
+ self.vision_feature_layer = vision_feature_layer
101
+
102
+ if isinstance(vision_config, dict):
103
+ vision_config["model_type"] = (
104
+ vision_config["model_type"] if "model_type" in vision_config else "clip_vision_model"
105
+ )
106
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
107
+ elif vision_config is None:
108
+ vision_config = CONFIG_MAPPING["clip_vision_model"](
109
+ intermediate_size=4096,
110
+ hidden_size=1024,
111
+ patch_size=14,
112
+ image_size=336,
113
+ num_hidden_layers=24,
114
+ num_attention_heads=16,
115
+ vocab_size=32000,
116
+ projection_dim=768,
117
+ )
118
+
119
+ self.vision_config = vision_config
120
+
121
+ if isinstance(text_config, dict):
122
+ text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "llama"
123
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
124
+ elif text_config is None:
125
+ text_config = CONFIG_MAPPING["llama"]()
126
+
127
+ self.text_config = text_config
128
+
129
+ if projector_hidden_size is None:
130
+ projector_hidden_size = text_config.hidden_size
131
+ self.projector_hidden_size = projector_hidden_size
132
+
133
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 99575,
6
+ "transformers_version": "4.45.2"
7
+ }
mmproj-model-f16.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eddf029d95058851c07b04d676d0b77038726033fde1a64ff58a5a9f50c85cac
3
+ size 860986368
modeling_llava.py ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Llava model."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+ from transformers import PreTrainedModel
24
+ from transformers.activations import ACT2FN
25
+ from transformers.cache_utils import Cache
26
+ from transformers.modeling_outputs import ModelOutput
27
+ from transformers.models.auto import AutoModel, AutoModelForCausalLM
28
+ from transformers.utils import (
29
+ add_start_docstrings,
30
+ add_start_docstrings_to_model_forward,
31
+ logging,
32
+ replace_return_docstrings,
33
+ )
34
+
35
+ from .configuration_llava import LlavaConfig
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ _CONFIG_FOR_DOC = "LlavaConfig"
40
+
41
+ # Base docstring
42
+ _CHECKPOINT_FOR_DOC = "llava-hf/llava-1.5-7b-hf"
43
+
44
+
45
+ @dataclass
46
+ # Copied from transformers.models.idefics.modeling_idefics.IdeficsCausalLMOutputWithPast with Idefics->Llava
47
+ class LlavaCausalLMOutputWithPast(ModelOutput):
48
+ """
49
+ Base class for Llava causal language model (or autoregressive) outputs.
50
+
51
+ Args:
52
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
53
+ Language modeling loss (for next-token prediction).
54
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
55
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
56
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed
57
+ or when `config.use_cache=True`):
58
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
59
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
60
+
61
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
62
+ `past_key_values` input) to speed up sequential decoding.
63
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed
64
+ or when `config.output_hidden_states=True`):
65
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
66
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
67
+
68
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
69
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed
70
+ or when `config.output_attentions=True`):
71
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
72
+ sequence_length)`.
73
+
74
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
75
+ heads.
76
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
77
+ Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
78
+ sequence_length, hidden_size)`.
79
+
80
+ image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
81
+ """
82
+
83
+ loss: Optional[torch.FloatTensor] = None
84
+ logits: torch.FloatTensor = None
85
+ past_key_values: Optional[List[torch.FloatTensor]] = None
86
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
87
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
88
+ image_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
89
+
90
+
91
+ class LlavaMultiModalProjector(nn.Module):
92
+ def __init__(self, config: LlavaConfig):
93
+ super().__init__()
94
+
95
+ self.linear_1 = nn.Linear(config.vision_config.hidden_size, config.projector_hidden_size, bias=True)
96
+ self.act = ACT2FN[config.projector_hidden_act]
97
+ self.linear_2 = nn.Linear(config.projector_hidden_size, config.text_config.hidden_size, bias=True)
98
+
99
+ def forward(self, image_features):
100
+ hidden_states = self.linear_1(image_features)
101
+ hidden_states = self.act(hidden_states)
102
+ hidden_states = self.linear_2(hidden_states)
103
+ return hidden_states
104
+
105
+
106
+ LLAVA_START_DOCSTRING = r"""
107
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
108
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
109
+ etc.)
110
+
111
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
112
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
113
+ and behavior.
114
+
115
+ Parameters:
116
+ config ([`LlavaConfig`] or [`LlavaVisionConfig`]):
117
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
118
+ load the weights associated with the model, only the configuration. Check out the
119
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
120
+ """
121
+
122
+
123
+ @add_start_docstrings(
124
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
125
+ LLAVA_START_DOCSTRING,
126
+ )
127
+ class LlavaPreTrainedModel(PreTrainedModel):
128
+ config_class = LlavaConfig
129
+ base_model_prefix = "model"
130
+ supports_gradient_checkpointing = True
131
+ _no_split_modules = ["LlavaVisionAttention"]
132
+ _skip_keys_device_placement = "past_key_values"
133
+ _supports_flash_attn_2 = True
134
+ _supports_cache_class = True
135
+
136
+ def _init_weights(self, module):
137
+ # important: this ported version of Llava isn't meant for training from scratch - only
138
+ # inference and fine-tuning - so the proper init weights code has been removed - the original codebase
139
+ # https://github.com/haotian-liu/LLaVA/tree/main/llava should serve for that purpose
140
+ std = (
141
+ self.config.initializer_range
142
+ if hasattr(self.config, "initializer_range")
143
+ else self.config.text_config.initializer_range
144
+ )
145
+
146
+ if hasattr(module, "class_embedding"):
147
+ module.class_embedding.data.normal_(mean=0.0, std=std)
148
+
149
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
150
+ module.weight.data.normal_(mean=0.0, std=std)
151
+ if module.bias is not None:
152
+ module.bias.data.zero_()
153
+ elif isinstance(module, nn.Embedding):
154
+ module.weight.data.normal_(mean=0.0, std=std)
155
+ if module.padding_idx is not None:
156
+ module.weight.data[module.padding_idx].zero_()
157
+
158
+ @property
159
+ def _supports_sdpa(self):
160
+ """
161
+ Retrieve language_model's attribute to check whether the model supports
162
+ SDPA or not.
163
+ """
164
+ return self.language_model._supports_sdpa
165
+
166
+
167
+ LLAVA_INPUTS_DOCSTRING = r"""
168
+ Args:
169
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
170
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
171
+ it.
172
+
173
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
174
+ [`PreTrainedTokenizer.__call__`] for details.
175
+
176
+ [What are input IDs?](../glossary#input-ids)
177
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
178
+ The tensors corresponding to the input images. Pixel values can be obtained using
179
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
180
+ [`CLIPImageProcessor`] for processing images).
181
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
182
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
183
+
184
+ - 1 for tokens that are **not masked**,
185
+ - 0 for tokens that are **masked**.
186
+
187
+ [What are attention masks?](../glossary#attention-mask)
188
+
189
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
190
+ [`PreTrainedTokenizer.__call__`] for details.
191
+
192
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
193
+ `past_key_values`).
194
+
195
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
196
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
197
+ information on the default strategy.
198
+
199
+ - 1 indicates the head is **not masked**,
200
+ - 0 indicates the head is **masked**.
201
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
202
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
203
+ config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
204
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed
205
+ or when `config.use_cache=True`):
206
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
207
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
208
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
209
+
210
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
211
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
212
+
213
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
214
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
215
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
216
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
217
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
218
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
219
+ model's internal embedding lookup matrix.
220
+ vision_feature_layer (`int`, *optional*, defaults to -2):
221
+ The index of the layer to select the vision feature.
222
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
223
+ The feature selection strategy used to select the vision feature from the vision backbone.
224
+ Can be one of `"default"` or `"full"`.
225
+ use_cache (`bool`, *optional*):
226
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
227
+ `past_key_values`).
228
+ output_attentions (`bool`, *optional*):
229
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
230
+ tensors for more detail.
231
+ output_hidden_states (`bool`, *optional*):
232
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
233
+ more detail.
234
+ return_dict (`bool`, *optional*):
235
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
236
+ """
237
+
238
+
239
+ @add_start_docstrings(
240
+ """The LLAVA model which consists of a vision backbone and a language model.""",
241
+ LLAVA_START_DOCSTRING,
242
+ )
243
+ class LlavaForConditionalGeneration(LlavaPreTrainedModel):
244
+ def __init__(self, config: LlavaConfig):
245
+ super().__init__(config)
246
+ self.vision_tower = AutoModel.from_config(config.vision_config)
247
+
248
+ self.multi_modal_projector = LlavaMultiModalProjector(config)
249
+ self.vocab_size = config.text_config.vocab_size
250
+ self.language_model = AutoModelForCausalLM.from_config(
251
+ config.text_config, attn_implementation=config._attn_implementation
252
+ )
253
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
254
+ self.post_init()
255
+
256
+ def get_input_embeddings(self):
257
+ return self.language_model.get_input_embeddings()
258
+
259
+ def set_input_embeddings(self, value):
260
+ self.language_model.set_input_embeddings(value)
261
+
262
+ def get_output_embeddings(self):
263
+ return self.language_model.get_output_embeddings()
264
+
265
+ def set_output_embeddings(self, new_embeddings):
266
+ self.language_model.set_output_embeddings(new_embeddings)
267
+
268
+ def set_decoder(self, decoder):
269
+ self.language_model.set_decoder(decoder)
270
+
271
+ def get_decoder(self):
272
+ return self.language_model.get_decoder()
273
+
274
+ def tie_weights(self):
275
+ return self.language_model.tie_weights()
276
+
277
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
278
+ model_embeds = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
279
+ # update vocab size
280
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
281
+ self.vocab_size = model_embeds.num_embeddings
282
+ return model_embeds
283
+
284
+ def _merge_input_ids_with_image_features(self, image_features, inputs_embeds, input_ids, attention_mask, labels):
285
+ num_images, num_image_patches, embed_dim = image_features.shape
286
+ batch_size, sequence_length = input_ids.shape
287
+ left_padding = not torch.sum(input_ids[:, -1] == torch.tensor(self.pad_token_id))
288
+ # 1. Create a mask to know where special image tokens are
289
+ special_image_token_mask = input_ids == self.config.image_token_index
290
+ num_special_image_tokens = torch.sum(special_image_token_mask, dim=-1)
291
+ # Compute the maximum embed dimension
292
+ max_embed_dim = (num_special_image_tokens.max() * (num_image_patches - 1)) + sequence_length
293
+ batch_indices, non_image_indices = torch.where(input_ids != self.config.image_token_index)
294
+
295
+ # 2. Compute the positions where text should be written
296
+ # Calculate new positions for text tokens in merged image-text sequence.
297
+ # `special_image_token_mask` identifies image tokens. Each image token will be replaced
298
+ # by `nb_text_tokens_per_images - 1` text tokens.
299
+ # `torch.cumsum` computes how each image token shifts subsequent text token positions.
300
+ # - 1 to adjust for zero-based indexing, as `cumsum` inherently increases indices by one.
301
+ new_token_positions = torch.cumsum((special_image_token_mask * (num_image_patches - 1) + 1), -1) - 1
302
+ nb_image_pad = max_embed_dim - 1 - new_token_positions[:, -1]
303
+ if left_padding:
304
+ new_token_positions += nb_image_pad[:, None] # offset for left padding
305
+ text_to_overwrite = new_token_positions[batch_indices, non_image_indices]
306
+
307
+ # 3. Create the full embedding, already padded to the maximum position
308
+ final_embedding = torch.zeros(
309
+ batch_size, max_embed_dim, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
310
+ )
311
+ final_attention_mask = torch.zeros(
312
+ batch_size, max_embed_dim, dtype=attention_mask.dtype, device=inputs_embeds.device
313
+ )
314
+ if labels is not None:
315
+ final_labels = torch.full(
316
+ (batch_size, max_embed_dim), self.config.ignore_index, dtype=input_ids.dtype, device=input_ids.device
317
+ )
318
+ # In case the Vision model or the Language model has been offloaded to CPU, we need to manually
319
+ # set the corresponding tensors into their correct target device.
320
+ target_device = inputs_embeds.device
321
+ batch_indices, non_image_indices, text_to_overwrite = (
322
+ batch_indices.to(target_device),
323
+ non_image_indices.to(target_device),
324
+ text_to_overwrite.to(target_device),
325
+ )
326
+ attention_mask = attention_mask.to(target_device)
327
+
328
+ # 4. Fill the embeddings based on the mask. If we have ["hey" "<image>", "how", "are"]
329
+ # we need to index copy on [0, 577, 578, 579] for the text and [1:576] for the image features
330
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_image_indices]
331
+ final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_image_indices]
332
+ if labels is not None:
333
+ final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_image_indices]
334
+
335
+ # 5. Fill the embeddings corresponding to the images.
336
+ # Anything that is not `text_positions` needs filling (#29835)
337
+ image_to_overwrite = torch.full(
338
+ (batch_size, max_embed_dim), True, dtype=torch.bool, device=inputs_embeds.device
339
+ )
340
+ image_to_overwrite[batch_indices, text_to_overwrite] = False
341
+ image_to_overwrite &= image_to_overwrite.cumsum(-1) - 1 >= nb_image_pad[:, None].to(target_device)
342
+
343
+ if image_to_overwrite.sum() != image_features.shape[:-1].numel():
344
+ raise ValueError(
345
+ f"The input provided to the model are wrong. "
346
+ f"The number of image tokens is {torch.sum(special_image_token_mask)} while"
347
+ f" the number of image given to the model is {num_images}. "
348
+ f"This prevents correct indexing and breaks batch generation."
349
+ )
350
+
351
+ final_embedding[image_to_overwrite] = image_features.contiguous().reshape(-1, embed_dim).to(target_device)
352
+ final_attention_mask |= image_to_overwrite
353
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
354
+
355
+ # 6. Mask out the embedding at padding positions, as we later use the past_key_value value
356
+ # to determine the non-attended tokens.
357
+ batch_indices, pad_indices = torch.where(input_ids == self.pad_token_id)
358
+ indices_to_mask = new_token_positions[batch_indices, pad_indices]
359
+
360
+ final_embedding[batch_indices, indices_to_mask] = 0
361
+
362
+ if labels is None:
363
+ final_labels = None
364
+
365
+ return final_embedding, final_attention_mask, final_labels, position_ids
366
+
367
+ @add_start_docstrings_to_model_forward(LLAVA_INPUTS_DOCSTRING)
368
+ @replace_return_docstrings(output_type=LlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
369
+ def forward(
370
+ self,
371
+ input_ids: torch.LongTensor = None,
372
+ pixel_values: torch.FloatTensor = None,
373
+ attention_mask: Optional[torch.Tensor] = None,
374
+ position_ids: Optional[torch.LongTensor] = None,
375
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
376
+ inputs_embeds: Optional[torch.FloatTensor] = None,
377
+ vision_feature_layer: Optional[int] = None,
378
+ vision_feature_select_strategy: Optional[str] = None,
379
+ labels: Optional[torch.LongTensor] = None,
380
+ use_cache: Optional[bool] = None,
381
+ output_attentions: Optional[bool] = None,
382
+ output_hidden_states: Optional[bool] = None,
383
+ return_dict: Optional[bool] = None,
384
+ ) -> Union[Tuple, LlavaCausalLMOutputWithPast]:
385
+ r"""
386
+ Args:
387
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
388
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
389
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
390
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
391
+
392
+ Returns:
393
+
394
+ Example:
395
+
396
+ ```python
397
+ >>> from PIL import Image
398
+ >>> import requests
399
+ >>> from transformers import AutoProcessor, LlavaForConditionalGeneration
400
+
401
+ >>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
402
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
403
+
404
+ >>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
405
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
406
+ >>> image = Image.open(requests.get(url, stream=True).raw)
407
+
408
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
409
+
410
+ >>> # Generate
411
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
412
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
413
+ "USER: \nWhat's the content of the image?
414
+ ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
415
+ ```"""
416
+
417
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
418
+ output_hidden_states = (
419
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
420
+ )
421
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
422
+ vision_feature_layer = (
423
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
424
+ )
425
+ vision_feature_select_strategy = (
426
+ vision_feature_select_strategy
427
+ if vision_feature_select_strategy is not None
428
+ else self.config.vision_feature_select_strategy
429
+ )
430
+
431
+ if inputs_embeds is None:
432
+ # 1. Extra the input embeddings
433
+ inputs_embeds = self.get_input_embeddings()(input_ids)
434
+
435
+ # 2. Merge text and images
436
+ if pixel_values is not None and input_ids.shape[1] != 1:
437
+ image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
438
+ # this is not memory efficient at all (output_hidden_states=True) will save all the hidden stated.
439
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
440
+
441
+ if vision_feature_select_strategy == "default":
442
+ selected_image_feature = selected_image_feature[:, 1:]
443
+ elif vision_feature_select_strategy == "full":
444
+ selected_image_feature = selected_image_feature
445
+ else:
446
+ raise ValueError(
447
+ f"Unexpected select feature strategy: {self.config.vision_feature_select_strategy}"
448
+ )
449
+
450
+ image_features = self.multi_modal_projector(selected_image_feature)
451
+ inputs_embeds = inputs_embeds.to(image_features.dtype)
452
+ inputs_embeds, attention_mask, labels, position_ids = self._merge_input_ids_with_image_features(
453
+ image_features, inputs_embeds, input_ids, attention_mask, labels
454
+ )
455
+
456
+ # In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
457
+ # generation with cache
458
+ elif past_key_values is not None and pixel_values is not None and input_ids.shape[1] == 1:
459
+ # Retrieve the first layer to inspect the logits and mask out the hidden states
460
+ # that are set to 0
461
+ first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]
462
+
463
+ # Sum all dimensions of head_dim (-2) to avoid random errors such as:
464
+ # https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941
465
+ batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)
466
+
467
+ # Get the target length
468
+ target_length = input_ids.shape[1]
469
+ past_length = first_layer_past_key_value.shape[-1]
470
+
471
+ extended_attention_mask = torch.ones(
472
+ (attention_mask.shape[0], past_length),
473
+ dtype=attention_mask.dtype,
474
+ device=attention_mask.device,
475
+ )
476
+
477
+ # Filter out only the tokens that can be un-attended, this can happen
478
+ # if one uses Llava + Fused modules where the cache on the
479
+ # first iteration is already big enough, or if one passes custom cache
480
+ valid_indices = non_attended_tokens < extended_attention_mask.size(-1)
481
+ new_batch_index = batch_index[valid_indices]
482
+ new_non_attended_tokens = non_attended_tokens[valid_indices]
483
+
484
+ # Zero-out the places where we don't need to attend
485
+ extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0
486
+
487
+ attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)
488
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
489
+
490
+ outputs = self.language_model(
491
+ attention_mask=attention_mask,
492
+ position_ids=position_ids,
493
+ past_key_values=past_key_values,
494
+ inputs_embeds=inputs_embeds,
495
+ use_cache=use_cache,
496
+ output_attentions=output_attentions,
497
+ output_hidden_states=output_hidden_states,
498
+ return_dict=return_dict,
499
+ )
500
+
501
+ logits = outputs[0]
502
+
503
+ loss = None
504
+ if labels is not None:
505
+ # Shift so that tokens < n predict n
506
+ if attention_mask is not None:
507
+ shift_attention_mask = attention_mask[..., 1:]
508
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
509
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
510
+ else:
511
+ shift_logits = logits[..., :-1, :].contiguous()
512
+ shift_labels = labels[..., 1:].contiguous()
513
+ # Flatten the tokens
514
+ loss_fct = nn.CrossEntropyLoss()
515
+ loss = loss_fct(
516
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
517
+ )
518
+
519
+ if not return_dict:
520
+ output = (logits,) + outputs[1:]
521
+ return (loss,) + output if loss is not None else output
522
+
523
+ return LlavaCausalLMOutputWithPast(
524
+ loss=loss,
525
+ logits=logits,
526
+ past_key_values=outputs.past_key_values,
527
+ hidden_states=outputs.hidden_states,
528
+ attentions=outputs.attentions,
529
+ )
530
+
531
+ def prepare_inputs_for_generation(
532
+ self, input_ids, past_key_values=None, inputs_embeds=None, pixel_values=None, attention_mask=None, **kwargs
533
+ ):
534
+ if past_key_values is not None:
535
+ if isinstance(past_key_values, Cache):
536
+ cache_length = past_key_values.get_seq_length()
537
+ past_length = past_key_values.seen_tokens
538
+ else:
539
+ cache_length = past_length = past_key_values[0][0].shape[2]
540
+
541
+ # Keep only the unprocessed tokens:
542
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
543
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
544
+ # input)
545
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
546
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
547
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
548
+ # input_ids based on the past_length.
549
+ elif past_length < input_ids.shape[1]:
550
+ input_ids = input_ids[:, past_length:]
551
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
552
+ elif self.config.image_token_index in input_ids:
553
+ input_ids = input_ids[:, input_ids.shape[1] - 1 :]
554
+ # If the cache has seen more tokens than it can hold, then the cache has a size limit. Let's discard the
555
+ # older attention values, as their corresponding values are not part of the input.
556
+ if cache_length < past_length and attention_mask is not None:
557
+ attention_mask = attention_mask[:, -(cache_length + input_ids.shape[1]) :]
558
+
559
+ position_ids = kwargs.get("position_ids", None)
560
+ if attention_mask is not None and position_ids is None:
561
+ # create position_ids on the fly for batch generation
562
+ position_ids = attention_mask.long().cumsum(-1) - 1
563
+ position_ids.masked_fill_(attention_mask == 0, 1)
564
+ if past_key_values:
565
+ position_ids = position_ids[:, -input_ids.shape[1] :]
566
+
567
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
568
+ if inputs_embeds is not None and past_key_values is None:
569
+ model_inputs = {"inputs_embeds": inputs_embeds}
570
+ else:
571
+ model_inputs = {"input_ids": input_ids}
572
+
573
+ model_inputs.update(
574
+ {
575
+ "position_ids": position_ids,
576
+ "past_key_values": past_key_values,
577
+ "use_cache": kwargs.get("use_cache"),
578
+ "attention_mask": attention_mask,
579
+ "pixel_values": pixel_values,
580
+ }
581
+ )
582
+ return model_inputs
583
+
584
+ def _reorder_cache(self, *args, **kwargs):
585
+ return self.language_model._reorder_cache(*args, **kwargs)
preprocessor_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_valid_processor_keys": [
3
+ "images",
4
+ "do_resize",
5
+ "size",
6
+ "resample",
7
+ "do_center_crop",
8
+ "crop_size",
9
+ "do_rescale",
10
+ "rescale_factor",
11
+ "do_normalize",
12
+ "image_mean",
13
+ "image_std",
14
+ "do_convert_rgb",
15
+ "return_tensors",
16
+ "data_format",
17
+ "input_data_format"
18
+ ],
19
+ "crop_size": {
20
+ "height": 384,
21
+ "width": 384
22
+ },
23
+ "do_center_crop": true,
24
+ "do_convert_rgb": true,
25
+ "do_normalize": true,
26
+ "do_rescale": true,
27
+ "do_resize": true,
28
+ "image_mean": [
29
+ 0.5,
30
+ 0.5,
31
+ 0.5
32
+ ],
33
+ "image_processor_type": "CLIPImageProcessor",
34
+ "image_std": [
35
+ 0.5,
36
+ 0.5,
37
+ 0.5
38
+ ],
39
+ "processor_class": "LlavaProcessor",
40
+ "resample": 3,
41
+ "rescale_factor": 0.00392156862745098,
42
+ "size": {
43
+ "height": 384,
44
+ "width": 384
45
+ }
46
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<image>",
4
+ "<pad>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "<s>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "cls_token": {
14
+ "content": "<CLS|LLM-jp>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "eos_token": {
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "mask_token": {
28
+ "content": "<MASK|LLM-jp>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ },
34
+ "pad_token": {
35
+ "content": "<pad>",
36
+ "lstrip": false,
37
+ "normalized": false,
38
+ "rstrip": false,
39
+ "single_word": false
40
+ },
41
+ "sep_token": {
42
+ "content": "<SEP|LLM-jp>",
43
+ "lstrip": false,
44
+ "normalized": false,
45
+ "rstrip": false,
46
+ "single_word": false
47
+ },
48
+ "unk_token": {
49
+ "content": "<unk>",
50
+ "lstrip": false,
51
+ "normalized": false,
52
+ "rstrip": false,
53
+ "single_word": false
54
+ }
55
+ }
text_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "llm-jp/llm-jp-3-1.8b-instruct",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "eos_token_id": 2,
10
+ "head_dim": 128,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 2048,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 7168,
15
+ "max_position_embeddings": 4096,
16
+ "mlp_bias": false,
17
+ "model_type": "llama",
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 24,
20
+ "num_key_value_heads": 16,
21
+ "pretraining_tp": 1,
22
+ "rms_norm_eps": 1e-05,
23
+ "rope_scaling": null,
24
+ "rope_theta": 10000,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.45.2",
28
+ "use_cache": true,
29
+ "vocab_size": 99584
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "3": {
30
+ "content": "<MASK|LLM-jp>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "4": {
38
+ "content": "<PAD|LLM-jp>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "5": {
46
+ "content": "<CLS|LLM-jp>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "6": {
54
+ "content": "<SEP|LLM-jp>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "7": {
62
+ "content": "<EOD|LLM-jp>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "99574": {
70
+ "content": "<image>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "99575": {
78
+ "content": "<pad>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ }
85
+ },
86
+ "additional_special_tokens": [
87
+ "<image>",
88
+ "<pad>"
89
+ ],
90
+ "bos_token": "<s>",
91
+ "chat_template": "{{bos_token}}{% for message in messages %}{% if message['role'] == 'user' %}{{ '\\n\\n### 指示:\\n' + message['content'] }}{% elif message['role'] == 'system' %}{{ '以下は、タスクを説明する指示です。要求を適切に満たす応答を書きなさい。' }}{% elif message['role'] == 'assistant' %}{{ '\\n\\n### 応答:\\n' + message['content'] + eos_token }}{% endif %}{% if loop.last and add_generation_prompt %}{{ '\\n\\n### 応答:\\n' }}{% endif %}{% endfor %}",
92
+ "clean_up_tokenization_spaces": false,
93
+ "cls_token": "<CLS|LLM-jp>",
94
+ "eod_token": "</s>",
95
+ "eos_token": "</s>",
96
+ "extra_ids": 0,
97
+ "mask_token": "<MASK|LLM-jp>",
98
+ "model_max_length": 1000000000000000019884624838656,
99
+ "pad_token": "<pad>",
100
+ "processor_class": "LlavaProcessor",
101
+ "sep_token": "<SEP|LLM-jp>",
102
+ "sp_model_kwargs": {},
103
+ "tokenizer_class": "PreTrainedTokenizerFast",
104
+ "unk_token": "<unk>"
105
+ }