HODACHI commited on
Commit
fa90ebf
·
verified ·
1 Parent(s): d318790

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +487 -148
README.md CHANGED
@@ -1,199 +1,538 @@
1
  ---
2
  library_name: transformers
3
- tags: []
 
 
 
4
  ---
5
 
6
- # Model Card for Model ID
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
9
 
10
 
 
 
11
 
12
- ## Model Details
 
13
 
14
- ### Model Description
 
15
 
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
 
72
- Use the code below to get started with the model.
 
73
 
74
- [More Information Needed]
75
 
76
- ## Training Details
77
 
78
- ### Training Data
 
79
 
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
 
82
- [More Information Needed]
83
 
84
- ### Training Procedure
85
 
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
 
87
 
88
- #### Preprocessing [optional]
89
 
90
- [More Information Needed]
91
 
92
 
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
 
139
- [More Information Needed]
140
 
141
- ## Environmental Impact
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
 
 
 
144
 
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
 
 
 
 
146
 
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
 
153
- ## Technical Specifications [optional]
154
 
155
- ### Model Architecture and Objective
 
 
156
 
157
- [More Information Needed]
 
 
 
 
 
158
 
159
- ### Compute Infrastructure
 
 
 
 
 
 
 
160
 
161
- [More Information Needed]
162
 
163
- #### Hardware
164
 
165
- [More Information Needed]
 
 
166
 
167
- #### Software
 
 
 
 
 
168
 
169
- [More Information Needed]
 
 
 
 
 
 
170
 
171
- ## Citation [optional]
 
 
172
 
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
 
174
 
175
- **BibTeX:**
 
 
176
 
177
- [More Information Needed]
178
 
179
- **APA:**
 
180
 
181
- [More Information Needed]
182
 
183
- ## Glossary [optional]
184
 
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
 
186
 
187
- [More Information Needed]
188
 
189
- ## More Information [optional]
190
 
191
- [More Information Needed]
 
 
 
 
 
192
 
193
- ## Model Card Authors [optional]
194
 
195
- [More Information Needed]
 
196
 
197
- ## Model Card Contact
 
198
 
199
- [More Information Needed]
 
1
  ---
2
  library_name: transformers
3
+ license: mit
4
+ language:
5
+ - ja
6
+ pipeline_tag: image-text-to-text
7
  ---
8
 
9
+ # [EZO model card]
10
 
11
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/657e900beaad53ff67ba84db/FrKFjIqieua3tD32CeECS.png)
12
 
13
 
14
+ ## [Model Information]
15
+ Based on the InternVL2-26B, this model has improved performance, especially in image recognition and Japanese language performance, by employing multiple tuning methods. It excels in Japanese language tasks, it's designed to meet diverse needs globally.
16
 
17
+ InternVL2-26Bをベースとして、複数のチューニング手法を採用のうえ、画像認識と日本語性能を中心に、性能を向上させたモデルです。
18
+ オープンソースモデルでは、2024. 08. 19時点で最高峰の日本語能力を備えており、同様の手法でトレーニングを行うことで、世界中の多様なニーズに応えることができる設計となっています。
19
 
20
+ ### [Benchmark Results]
21
+ TODO:
22
 
23
+ **Terms of Use**:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ This model is based on InternVL2-26B and is Mit.
26
+ このモデルはInternVL2-26Bをベースにしており、Mitとしています。
27
 
28
+ ### 推奨される使用ガイドライン / Recommended Usage Guidelines
29
 
30
+ 1. **商用利用**: 本モデルを商用目的で使用する場合、info@axcxept.com へのメール連絡を強く推奨します。これにより、モデルの応用や改善についての協力の機会が生まれる可能性があります。
31
 
32
+ 2. **クレジット表記**: 本モデルを使用または改変する際は、以下のようなクレジット表記を行うことを推奨します:
33
+ "This project utilizes HODACHI/EZO-InternVL2-26B, a model based on OpenGVLab/InternVL2-26B and fine-tuned by Axcxept co., ltd."
34
 
35
+ 3. **フィードバック**: モデルの使用経験に関するフィードバックを歓迎します。info@axcxept.com までご連絡ください。
36
 
37
+ これらは推奨事項であり、法的要件ではありません。本モデルの使用は主に Mit に準拠します。
38
 
39
+ 1. **Commercial Use**: If you intend to use this model for commercial purposes, we strongly encourage you to contact us by email at info@axcxept.com. This may create opportunities for collaboration on applications and improvements of the model. 2.
40
 
41
+ 2.**Credit notation**: When using or modifying the model, it is recommended that the following credit be given: “This project utilizes HODAC:
42
+ ���This project utilizes HODACHI/EZO-InternVL2-26B, a model based on OpenGVLab/InternVL2-26B and fine-tuned by Axcxept co. ltd.”
43
 
44
+ 3.**Feedback**: We welcome feedback on your experience with the model, please contact us at info@axcxept.com.
45
 
46
+ These are recommendations, not legal requirements. Use of this model is primarily governed by Mit.
47
 
48
 
49
+ <!-- Provide a longer summary of what this model is. -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
52
 
53
+ - **Developed by:** Axcxept co., ltd.
54
+ - **Language(s) (NLP): English, Japanese
55
+
56
+ ## [Usage]
57
+
58
+ ### INSTALL
59
+
60
+ `
61
+ pip install -U transformers==4.37.2 sentencepiece
62
+ `
63
+
64
+
65
+ ### Model Loading
66
+
67
+ #### 16-bit (bf16 / fp16)
68
+
69
+ ```python
70
+ import torch
71
+ from transformers import AutoTokenizer, AutoModel
72
+ path = "HODACHI/EZO-InternVL2-26B"
73
+ model = AutoModel.from_pretrained(
74
+ path,
75
+ torch_dtype=torch.bfloat16,
76
+ low_cpu_mem_usage=True,
77
+ trust_remote_code=True).eval().cuda()
78
+ ```
79
+
80
+ #### BNB 8-bit Quantization
81
+
82
+ ```python
83
+ import torch
84
+ from transformers import AutoTokenizer, AutoModel
85
+ path = "HODACHI/EZO-InternVL2-26B"
86
+ model = AutoModel.from_pretrained(
87
+ path,
88
+ torch_dtype=torch.bfloat16,
89
+ load_in_8bit=True,
90
+ low_cpu_mem_usage=True,
91
+ trust_remote_code=True).eval()
92
+ ```
93
+
94
+ #### BNB 4-bit Quantization
95
+
96
+ > **⚠️ Warning:** Due to significant quantization errors with BNB 4-bit quantization on InternViT-6B, the model may produce nonsensical outputs and fail to understand images. Therefore, please avoid using BNB 4-bit quantization.
97
+
98
+ #### Multiple GPUs
99
+
100
+ The reason for writing the code this way is to avoid errors that occur during multi-GPU inference due to tensors not being on the same device. By ensuring that the first and last layers of the large language model (LLM) are on the same device, we prevent such errors.
101
+
102
+ ```python
103
+ import math
104
+ import torch
105
+ from transformers import AutoTokenizer, AutoModel
106
+
107
+ def split_model(model_name):
108
+ device_map = {}
109
+ world_size = torch.cuda.device_count()
110
+ num_layers = {
111
+ 'InternVL2-1B': 24, 'InternVL2-2B': 24, 'InternVL2-4B': 32, 'InternVL2-8B': 32,
112
+ 'InternVL2-26B': 48, 'InternVL2-40B': 60, 'InternVL2-Llama3-76B': 80}[model_name]
113
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
114
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
115
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
116
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
117
+ layer_cnt = 0
118
+ for i, num_layer in enumerate(num_layers_per_gpu):
119
+ for j in range(num_layer):
120
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
121
+ layer_cnt += 1
122
+ device_map['vision_model'] = 0
123
+ device_map['mlp1'] = 0
124
+ device_map['language_model.model.tok_embeddings'] = 0
125
+ device_map['language_model.model.embed_tokens'] = 0
126
+ device_map['language_model.output'] = 0
127
+ device_map['language_model.model.norm'] = 0
128
+ device_map['language_model.lm_head'] = 0
129
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
130
+
131
+ return device_map
132
+
133
+ path = "HODACHI/EZO-InternVL2-26B"
134
+ device_map = split_model('InternVL2-26B')
135
+ model = AutoModel.from_pretrained(
136
+ path,
137
+ torch_dtype=torch.bfloat16,
138
+ low_cpu_mem_usage=True,
139
+ trust_remote_code=True,
140
+ device_map=device_map).eval()
141
+ ```
142
+
143
+ ### Inference with Transformers
144
+
145
+ ```python
146
+ import numpy as np
147
+ import torch
148
+ import torchvision.transforms as T
149
+ from decord import VideoReader, cpu
150
+ from PIL import Image
151
+ from torchvision.transforms.functional import InterpolationMode
152
+ from transformers import AutoModel, AutoTokenizer
153
+
154
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
155
+ IMAGENET_STD = (0.229, 0.224, 0.225)
156
+
157
+ def build_transform(input_size):
158
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
159
+ transform = T.Compose([
160
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
161
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
162
+ T.ToTensor(),
163
+ T.Normalize(mean=MEAN, std=STD)
164
+ ])
165
+ return transform
166
+
167
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
168
+ best_ratio_diff = float('inf')
169
+ best_ratio = (1, 1)
170
+ area = width * height
171
+ for ratio in target_ratios:
172
+ target_aspect_ratio = ratio[0] / ratio[1]
173
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
174
+ if ratio_diff < best_ratio_diff:
175
+ best_ratio_diff = ratio_diff
176
+ best_ratio = ratio
177
+ elif ratio_diff == best_ratio_diff:
178
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
179
+ best_ratio = ratio
180
+ return best_ratio
181
+
182
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
183
+ orig_width, orig_height = image.size
184
+ aspect_ratio = orig_width / orig_height
185
+
186
+ # calculate the existing image aspect ratio
187
+ target_ratios = set(
188
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
189
+ i * j <= max_num and i * j >= min_num)
190
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
191
+
192
+ # find the closest aspect ratio to the target
193
+ target_aspect_ratio = find_closest_aspect_ratio(
194
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
195
+
196
+ # calculate the target width and height
197
+ target_width = image_size * target_aspect_ratio[0]
198
+ target_height = image_size * target_aspect_ratio[1]
199
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
200
+
201
+ # resize the image
202
+ resized_img = image.resize((target_width, target_height))
203
+ processed_images = []
204
+ for i in range(blocks):
205
+ box = (
206
+ (i % (target_width // image_size)) * image_size,
207
+ (i // (target_width // image_size)) * image_size,
208
+ ((i % (target_width // image_size)) + 1) * image_size,
209
+ ((i // (target_width // image_size)) + 1) * image_size
210
+ )
211
+ # split the image
212
+ split_img = resized_img.crop(box)
213
+ processed_images.append(split_img)
214
+ assert len(processed_images) == blocks
215
+ if use_thumbnail and len(processed_images) != 1:
216
+ thumbnail_img = image.resize((image_size, image_size))
217
+ processed_images.append(thumbnail_img)
218
+ return processed_images
219
+
220
+ def load_image(image_file, input_size=448, max_num=12):
221
+ image = Image.open(image_file).convert('RGB')
222
+ transform = build_transform(input_size=input_size)
223
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
224
+ pixel_values = [transform(image) for image in images]
225
+ pixel_values = torch.stack(pixel_values)
226
+ return pixel_values
227
+
228
+ # If you have an 80G A100 GPU, you can put the entire model on a single GPU.
229
+ # Otherwise, you need to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
230
+ path = 'HODACHI/EZO-InternVL2-26B'
231
+ model = AutoModel.from_pretrained(
232
+ path,
233
+ torch_dtype=torch.bfloat16,
234
+ low_cpu_mem_usage=True,
235
+ trust_remote_code=True).eval().cuda()
236
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
237
+
238
+ # set the max number of tiles in `max_num`
239
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
240
+ generation_config = dict(max_new_tokens=1024, do_sample=False)
241
+
242
+ # pure-text conversation (纯文本对话)
243
+ question = 'Hello, who are you?'
244
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
245
+ print(f'User: {question}\nAssistant: {response}')
246
+
247
+ question = 'Can you tell me a story?'
248
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
249
+ print(f'User: {question}\nAssistant: {response}')
250
+
251
+ # single-image single-round conversation (单图单轮对话)
252
+ question = '<image>\nPlease describe the image shortly.'
253
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
254
+ print(f'User: {question}\nAssistant: {response}')
255
+
256
+ # single-image multi-round conversation (单图多轮对话)
257
+ question = '<image>\nPlease describe the image in detail.'
258
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
259
+ print(f'User: {question}\nAssistant: {response}')
260
+
261
+ question = 'Please write a poem according to the image.'
262
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
263
+ print(f'User: {question}\nAssistant: {response}')
264
+
265
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
266
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
267
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
268
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
269
+
270
+ question = '<image>\nDescribe the two images in detail.'
271
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
272
+ history=None, return_history=True)
273
+ print(f'User: {question}\nAssistant: {response}')
274
+
275
+ question = 'What are the similarities and differences between these two images.'
276
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
277
+ history=history, return_history=True)
278
+ print(f'User: {question}\nAssistant: {response}')
279
+
280
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
281
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
282
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
283
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
284
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
285
+
286
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
287
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
288
+ num_patches_list=num_patches_list,
289
+ history=None, return_history=True)
290
+ print(f'User: {question}\nAssistant: {response}')
291
+
292
+ question = 'What are the similarities and differences between these two images.'
293
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
294
+ num_patches_list=num_patches_list,
295
+ history=history, return_history=True)
296
+ print(f'User: {question}\nAssistant: {response}')
297
+
298
+ # batch inference, single image per sample (单图批处理)
299
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
300
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
301
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
302
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
303
+
304
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
305
+ responses = model.batch_chat(tokenizer, pixel_values,
306
+ num_patches_list=num_patches_list,
307
+ questions=questions,
308
+ generation_config=generation_config)
309
+ for question, response in zip(questions, responses):
310
+ print(f'User: {question}\nAssistant: {response}')
311
+
312
+ # video multi-round conversation (视频多轮对话)
313
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
314
+ if bound:
315
+ start, end = bound[0], bound[1]
316
+ else:
317
+ start, end = -100000, 100000
318
+ start_idx = max(first_idx, round(start * fps))
319
+ end_idx = min(round(end * fps), max_frame)
320
+ seg_size = float(end_idx - start_idx) / num_segments
321
+ frame_indices = np.array([
322
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
323
+ for idx in range(num_segments)
324
+ ])
325
+ return frame_indices
326
+
327
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
328
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
329
+ max_frame = len(vr) - 1
330
+ fps = float(vr.get_avg_fps())
331
+
332
+ pixel_values_list, num_patches_list = [], []
333
+ transform = build_transform(input_size=input_size)
334
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
335
+ for frame_index in frame_indices:
336
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
337
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
338
+ pixel_values = [transform(tile) for tile in img]
339
+ pixel_values = torch.stack(pixel_values)
340
+ num_patches_list.append(pixel_values.shape[0])
341
+ pixel_values_list.append(pixel_values)
342
+ pixel_values = torch.cat(pixel_values_list)
343
+ return pixel_values, num_patches_list
344
+
345
+ video_path = './examples/red-panda.mp4'
346
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
347
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
348
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
349
+ question = video_prefix + 'What is the red panda doing?'
350
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
351
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
352
+ num_patches_list=num_patches_list, history=None, return_history=True)
353
+ print(f'User: {question}\nAssistant: {response}')
354
+
355
+ question = 'Describe this video in detail. Don\'t repeat.'
356
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
357
+ num_patches_list=num_patches_list, history=history, return_history=True)
358
+ print(f'User: {question}\nAssistant: {response}')
359
+ ```
360
+
361
+ #### Streaming output
362
+
363
+ Besides this method, you can also use the following code to get streamed output.
364
+
365
+ ```python
366
+ from transformers import TextIteratorStreamer
367
+ from threading import Thread
368
+
369
+ # Initialize the streamer
370
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
371
+ # Define the generation configuration
372
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
373
+ # Start the model chat in a separate thread
374
+ thread = Thread(target=model.chat, kwargs=dict(
375
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
376
+ history=None, return_history=False, generation_config=generation_config,
377
+ ))
378
+ thread.start()
379
+
380
+ # Initialize an empty string to store the generated text
381
+ generated_text = ''
382
+ # Loop through the streamer to get the new text as it is generated
383
+ for new_text in streamer:
384
+ if new_text == model.conv_template.sep:
385
+ break
386
+ generated_text += new_text
387
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
388
+ ```
389
+
390
+ ## Finetune
391
+
392
+ SWIFT from ModelScope community has supported the fine-tuning (Image/Video) of InternVL, please check [this link](https://github.com/modelscope/swift/blob/main/docs/source_en/Multi-Modal/internvl-best-practice.md) for more details.
393
+
394
+ ## Deployment
395
+
396
+ ### LMDeploy
397
+
398
+ LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
399
+
400
+ ```sh
401
+ pip install lmdeploy
402
+ ```
403
+
404
+ LMDeploy abstracts the complex inference process of multi-modal Vision-Language Models (VLM) into an easy-to-use pipeline, similar to the Large Language Model (LLM) inference pipeline.
405
+
406
+ #### A 'Hello, world' example
407
+
408
+ ```python
409
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
410
+ from lmdeploy.vl import load_image
411
+
412
+ model = 'HODACHI/EZO-InternVL2-26B'
413
+ system_prompt = 'あなたは優秀な、マルチモーダル大規模言語モデルである。'
414
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
415
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
416
+ chat_template_config.meta_instruction = system_prompt
417
+ pipe = pipeline(model, chat_template_config=chat_template_config,
418
+ backend_config=TurbomindEngineConfig(session_len=8192))
419
+ response = pipe(('describe this image', image))
420
+ print(response.text)
421
+ ```
422
+
423
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
424
+
425
+ #### Multi-images inference
426
+
427
+ When dealing with multiple images, you can put them all in one list. Keep in mind that multiple images will lead to a higher number of input tokens, and as a result, the size of the context window typically needs to be increased.
428
+
429
+ > Warning: Due to the scarcity of multi-image conversation data, the performance on multi-image tasks may be unstable, and it may require multiple attempts to achieve satisfactory results.
430
+
431
+ ```python
432
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
433
+ from lmdeploy.vl import load_image
434
+ from lmdeploy.vl.constants import IMAGE_TOKEN
435
+
436
+ model = 'HODACHI/EZO-InternVL2-26B'
437
+ system_prompt = 'あなたは優秀な、マルチモーダル大規模言語モデルである。'
438
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
439
+ chat_template_config.meta_instruction = system_prompt
440
+ pipe = pipeline(model, chat_template_config=chat_template_config,
441
+ backend_config=TurbomindEngineConfig(session_len=8192))
442
 
443
+ image_urls=[
444
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
445
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
446
+ ]
447
 
448
+ images = [load_image(img_url) for img_url in image_urls]
449
+ # Numbering images improves multi-image conversations
450
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
451
+ print(response.text)
452
+ ```
453
 
454
+ #### Batch prompts inference
 
 
 
 
455
 
456
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
457
 
458
+ ```python
459
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
460
+ from lmdeploy.vl import load_image
461
 
462
+ model = 'HODACHI/EZO-InternVL2-26B'
463
+ system_prompt = 'あなたは優秀な、マルチモーダル大規模言語モデルである。'
464
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
465
+ chat_template_config.meta_instruction = system_prompt
466
+ pipe = pipeline(model, chat_template_config=chat_template_config,
467
+ backend_config=TurbomindEngineConfig(session_len=8192))
468
 
469
+ image_urls=[
470
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
471
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
472
+ ]
473
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
474
+ response = pipe(prompts)
475
+ print(response)
476
+ ```
477
 
478
+ #### Multi-turn conversation
479
 
480
+ There are two ways to do the multi-turn conversations with the pipeline. One is to construct messages according to the format of OpenAI and use above introduced method, the other is to use the `pipeline.chat` interface.
481
 
482
+ ```python
483
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig, GenerationConfig
484
+ from lmdeploy.vl import load_image
485
 
486
+ model = 'HODACHI/EZO-InternVL2-26B'
487
+ system_prompt = 'あなたは優秀な、マルチモーダル大規模言語モデルです'
488
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
489
+ chat_template_config.meta_instruction = system_prompt
490
+ pipe = pipeline(model, chat_template_config=chat_template_config,
491
+ backend_config=TurbomindEngineConfig(session_len=8192))
492
 
493
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
494
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
495
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
496
+ print(sess.response.text)
497
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
498
+ print(sess.response.text)
499
+ ```
500
 
501
+ ### [Model Data]
502
+ #### Training Dataset]
503
+ We extracted high-quality data from Japanese Wikipedia and FineWeb to create instruction data. Our innovative training approach allows for performance improvements across various languages and domains, making the model suitable for global use despite its focus on Japanese data.
504
 
505
+ 日本語のWikiデータおよび、FineWebから良質なデータ、画像分類を抽出し、Instructionデータを作成しました。
506
+ このモデルでは日本語に特化させていますが、世界中のどんなユースケースでも利用可能なアプローチです。
507
 
508
+ https://huggingface.co/datasets/legacy-datasets/wikipedia
509
+ https://huggingface.co/datasets/HuggingFaceFW/fineweb
510
+ https://huggingface.co/datasets/STIC-LVLM/stic-coco-preference-6k/blob/main/images.zip
511
 
 
512
 
513
+ #### Data Preprocessing
514
+ We used a plain instruction tuning method to train the model on exemplary responses. This approach enhances the model's ability to understand and generate high-quality responses across various languages and contexts.
515
 
516
+ プレインストラクトチューニング手法を用いて、模範的回答を学習させました。この手法により、モデルは様々な言語やコンテキストにおいて高品質な応答を理解し生成する能力が向上しています。
517
 
 
518
 
519
+ #### Implementation Information
520
+ [Pre-Instruction Training]
521
 
522
+ https://huggingface.co/instruction-pretrain/instruction-synthesizer
523
 
 
524
 
525
+ ### [Disclaimer]
526
+ このモデルは研究開発のみを目的として提供されるものであり、実験的なプロトタイプとみなされるべきモデルです。
527
+ 商業的な使用やミッションクリティカルな環境への配備を意図したものではありません。
528
+ 本モデルの使用は、使用者の責任において行われるものとし、その性能および結果は保証されません。
529
+ Axcxept株式会社は、直接的、間接的、特別、偶発的、結果的な損害、または本モデルの使用から生じるいかなる損失に対しても、得られた結果にかかわらず、一切の責任を負いません。
530
+ 利用者は、本モデルの使用に伴うリスクを十分に理解し、自己の判断で使用するものとします。
531
 
 
532
 
533
+ ### [Hardware]
534
+ H100 × 8(Running in 8h)
535
 
536
+ ### [We are.]
537
+ [![Axcxept logo](https://cdn-uploads.huggingface.co/production/uploads/657e900beaad53ff67ba84db/8OKW86U986ywttvL2RcbG.png)](https://axcxept.com)
538