mgoin commited on
Commit
259271f
1 Parent(s): d3fb148

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
config.json ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": "732e07409dd594a7c8b4e178acde3e821f34c5c0",
3
+ "_name_or_path": "/home/mgoin/.cache/huggingface/hub/models--nvidia--NVLM-D-72B/snapshots/732e07409dd594a7c8b4e178acde3e821f34c5c0",
4
+ "architectures": [
5
+ "NVLM_D"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_nvlm_d.NVLM_D_Config",
9
+ "AutoModel": "modeling_nvlm_d.NVLM_D_Model",
10
+ "AutoModelForCausalLM": "modeling_nvlm_d.NVLM_D_Model"
11
+ },
12
+ "compression_config": {
13
+ "config_groups": {
14
+ "group_0": {
15
+ "input_activations": {
16
+ "actorder": null,
17
+ "block_structure": null,
18
+ "dynamic": true,
19
+ "group_size": null,
20
+ "num_bits": 8,
21
+ "observer": "memoryless",
22
+ "observer_kwargs": {},
23
+ "strategy": "token",
24
+ "symmetric": true,
25
+ "type": "float"
26
+ },
27
+ "output_activations": null,
28
+ "targets": [
29
+ "Linear"
30
+ ],
31
+ "weights": {
32
+ "actorder": null,
33
+ "block_structure": null,
34
+ "dynamic": false,
35
+ "group_size": null,
36
+ "num_bits": 8,
37
+ "observer": "minmax",
38
+ "observer_kwargs": {},
39
+ "strategy": "channel",
40
+ "symmetric": true,
41
+ "type": "float"
42
+ }
43
+ }
44
+ },
45
+ "format": "float-quantized",
46
+ "global_compression_ratio": 1.1596271208975781,
47
+ "ignore": [
48
+ "vision_model.encoder.layers.0.attn.qkv",
49
+ "vision_model.encoder.layers.0.attn.proj",
50
+ "vision_model.encoder.layers.0.mlp.fc1",
51
+ "vision_model.encoder.layers.0.mlp.fc2",
52
+ "vision_model.encoder.layers.1.attn.qkv",
53
+ "vision_model.encoder.layers.1.attn.proj",
54
+ "vision_model.encoder.layers.1.mlp.fc1",
55
+ "vision_model.encoder.layers.1.mlp.fc2",
56
+ "vision_model.encoder.layers.2.attn.qkv",
57
+ "vision_model.encoder.layers.2.attn.proj",
58
+ "vision_model.encoder.layers.2.mlp.fc1",
59
+ "vision_model.encoder.layers.2.mlp.fc2",
60
+ "vision_model.encoder.layers.3.attn.qkv",
61
+ "vision_model.encoder.layers.3.attn.proj",
62
+ "vision_model.encoder.layers.3.mlp.fc1",
63
+ "vision_model.encoder.layers.3.mlp.fc2",
64
+ "vision_model.encoder.layers.4.attn.qkv",
65
+ "vision_model.encoder.layers.4.attn.proj",
66
+ "vision_model.encoder.layers.4.mlp.fc1",
67
+ "vision_model.encoder.layers.4.mlp.fc2",
68
+ "vision_model.encoder.layers.5.attn.qkv",
69
+ "vision_model.encoder.layers.5.attn.proj",
70
+ "vision_model.encoder.layers.5.mlp.fc1",
71
+ "vision_model.encoder.layers.5.mlp.fc2",
72
+ "vision_model.encoder.layers.6.attn.qkv",
73
+ "vision_model.encoder.layers.6.attn.proj",
74
+ "vision_model.encoder.layers.6.mlp.fc1",
75
+ "vision_model.encoder.layers.6.mlp.fc2",
76
+ "vision_model.encoder.layers.7.attn.qkv",
77
+ "vision_model.encoder.layers.7.attn.proj",
78
+ "vision_model.encoder.layers.7.mlp.fc1",
79
+ "vision_model.encoder.layers.7.mlp.fc2",
80
+ "vision_model.encoder.layers.8.attn.qkv",
81
+ "vision_model.encoder.layers.8.attn.proj",
82
+ "vision_model.encoder.layers.8.mlp.fc1",
83
+ "vision_model.encoder.layers.8.mlp.fc2",
84
+ "vision_model.encoder.layers.9.attn.qkv",
85
+ "vision_model.encoder.layers.9.attn.proj",
86
+ "vision_model.encoder.layers.9.mlp.fc1",
87
+ "vision_model.encoder.layers.9.mlp.fc2",
88
+ "vision_model.encoder.layers.10.attn.qkv",
89
+ "vision_model.encoder.layers.10.attn.proj",
90
+ "vision_model.encoder.layers.10.mlp.fc1",
91
+ "vision_model.encoder.layers.10.mlp.fc2",
92
+ "vision_model.encoder.layers.11.attn.qkv",
93
+ "vision_model.encoder.layers.11.attn.proj",
94
+ "vision_model.encoder.layers.11.mlp.fc1",
95
+ "vision_model.encoder.layers.11.mlp.fc2",
96
+ "vision_model.encoder.layers.12.attn.qkv",
97
+ "vision_model.encoder.layers.12.attn.proj",
98
+ "vision_model.encoder.layers.12.mlp.fc1",
99
+ "vision_model.encoder.layers.12.mlp.fc2",
100
+ "vision_model.encoder.layers.13.attn.qkv",
101
+ "vision_model.encoder.layers.13.attn.proj",
102
+ "vision_model.encoder.layers.13.mlp.fc1",
103
+ "vision_model.encoder.layers.13.mlp.fc2",
104
+ "vision_model.encoder.layers.14.attn.qkv",
105
+ "vision_model.encoder.layers.14.attn.proj",
106
+ "vision_model.encoder.layers.14.mlp.fc1",
107
+ "vision_model.encoder.layers.14.mlp.fc2",
108
+ "vision_model.encoder.layers.15.attn.qkv",
109
+ "vision_model.encoder.layers.15.attn.proj",
110
+ "vision_model.encoder.layers.15.mlp.fc1",
111
+ "vision_model.encoder.layers.15.mlp.fc2",
112
+ "vision_model.encoder.layers.16.attn.qkv",
113
+ "vision_model.encoder.layers.16.attn.proj",
114
+ "vision_model.encoder.layers.16.mlp.fc1",
115
+ "vision_model.encoder.layers.16.mlp.fc2",
116
+ "vision_model.encoder.layers.17.attn.qkv",
117
+ "vision_model.encoder.layers.17.attn.proj",
118
+ "vision_model.encoder.layers.17.mlp.fc1",
119
+ "vision_model.encoder.layers.17.mlp.fc2",
120
+ "vision_model.encoder.layers.18.attn.qkv",
121
+ "vision_model.encoder.layers.18.attn.proj",
122
+ "vision_model.encoder.layers.18.mlp.fc1",
123
+ "vision_model.encoder.layers.18.mlp.fc2",
124
+ "vision_model.encoder.layers.19.attn.qkv",
125
+ "vision_model.encoder.layers.19.attn.proj",
126
+ "vision_model.encoder.layers.19.mlp.fc1",
127
+ "vision_model.encoder.layers.19.mlp.fc2",
128
+ "vision_model.encoder.layers.20.attn.qkv",
129
+ "vision_model.encoder.layers.20.attn.proj",
130
+ "vision_model.encoder.layers.20.mlp.fc1",
131
+ "vision_model.encoder.layers.20.mlp.fc2",
132
+ "vision_model.encoder.layers.21.attn.qkv",
133
+ "vision_model.encoder.layers.21.attn.proj",
134
+ "vision_model.encoder.layers.21.mlp.fc1",
135
+ "vision_model.encoder.layers.21.mlp.fc2",
136
+ "vision_model.encoder.layers.22.attn.qkv",
137
+ "vision_model.encoder.layers.22.attn.proj",
138
+ "vision_model.encoder.layers.22.mlp.fc1",
139
+ "vision_model.encoder.layers.22.mlp.fc2",
140
+ "vision_model.encoder.layers.23.attn.qkv",
141
+ "vision_model.encoder.layers.23.attn.proj",
142
+ "vision_model.encoder.layers.23.mlp.fc1",
143
+ "vision_model.encoder.layers.23.mlp.fc2",
144
+ "vision_model.encoder.layers.24.attn.qkv",
145
+ "vision_model.encoder.layers.24.attn.proj",
146
+ "vision_model.encoder.layers.24.mlp.fc1",
147
+ "vision_model.encoder.layers.24.mlp.fc2",
148
+ "vision_model.encoder.layers.25.attn.qkv",
149
+ "vision_model.encoder.layers.25.attn.proj",
150
+ "vision_model.encoder.layers.25.mlp.fc1",
151
+ "vision_model.encoder.layers.25.mlp.fc2",
152
+ "vision_model.encoder.layers.26.attn.qkv",
153
+ "vision_model.encoder.layers.26.attn.proj",
154
+ "vision_model.encoder.layers.26.mlp.fc1",
155
+ "vision_model.encoder.layers.26.mlp.fc2",
156
+ "vision_model.encoder.layers.27.attn.qkv",
157
+ "vision_model.encoder.layers.27.attn.proj",
158
+ "vision_model.encoder.layers.27.mlp.fc1",
159
+ "vision_model.encoder.layers.27.mlp.fc2",
160
+ "vision_model.encoder.layers.28.attn.qkv",
161
+ "vision_model.encoder.layers.28.attn.proj",
162
+ "vision_model.encoder.layers.28.mlp.fc1",
163
+ "vision_model.encoder.layers.28.mlp.fc2",
164
+ "vision_model.encoder.layers.29.attn.qkv",
165
+ "vision_model.encoder.layers.29.attn.proj",
166
+ "vision_model.encoder.layers.29.mlp.fc1",
167
+ "vision_model.encoder.layers.29.mlp.fc2",
168
+ "vision_model.encoder.layers.30.attn.qkv",
169
+ "vision_model.encoder.layers.30.attn.proj",
170
+ "vision_model.encoder.layers.30.mlp.fc1",
171
+ "vision_model.encoder.layers.30.mlp.fc2",
172
+ "vision_model.encoder.layers.31.attn.qkv",
173
+ "vision_model.encoder.layers.31.attn.proj",
174
+ "vision_model.encoder.layers.31.mlp.fc1",
175
+ "vision_model.encoder.layers.31.mlp.fc2",
176
+ "vision_model.encoder.layers.32.attn.qkv",
177
+ "vision_model.encoder.layers.32.attn.proj",
178
+ "vision_model.encoder.layers.32.mlp.fc1",
179
+ "vision_model.encoder.layers.32.mlp.fc2",
180
+ "vision_model.encoder.layers.33.attn.qkv",
181
+ "vision_model.encoder.layers.33.attn.proj",
182
+ "vision_model.encoder.layers.33.mlp.fc1",
183
+ "vision_model.encoder.layers.33.mlp.fc2",
184
+ "vision_model.encoder.layers.34.attn.qkv",
185
+ "vision_model.encoder.layers.34.attn.proj",
186
+ "vision_model.encoder.layers.34.mlp.fc1",
187
+ "vision_model.encoder.layers.34.mlp.fc2",
188
+ "vision_model.encoder.layers.35.attn.qkv",
189
+ "vision_model.encoder.layers.35.attn.proj",
190
+ "vision_model.encoder.layers.35.mlp.fc1",
191
+ "vision_model.encoder.layers.35.mlp.fc2",
192
+ "vision_model.encoder.layers.36.attn.qkv",
193
+ "vision_model.encoder.layers.36.attn.proj",
194
+ "vision_model.encoder.layers.36.mlp.fc1",
195
+ "vision_model.encoder.layers.36.mlp.fc2",
196
+ "vision_model.encoder.layers.37.attn.qkv",
197
+ "vision_model.encoder.layers.37.attn.proj",
198
+ "vision_model.encoder.layers.37.mlp.fc1",
199
+ "vision_model.encoder.layers.37.mlp.fc2",
200
+ "vision_model.encoder.layers.38.attn.qkv",
201
+ "vision_model.encoder.layers.38.attn.proj",
202
+ "vision_model.encoder.layers.38.mlp.fc1",
203
+ "vision_model.encoder.layers.38.mlp.fc2",
204
+ "vision_model.encoder.layers.39.attn.qkv",
205
+ "vision_model.encoder.layers.39.attn.proj",
206
+ "vision_model.encoder.layers.39.mlp.fc1",
207
+ "vision_model.encoder.layers.39.mlp.fc2",
208
+ "vision_model.encoder.layers.40.attn.qkv",
209
+ "vision_model.encoder.layers.40.attn.proj",
210
+ "vision_model.encoder.layers.40.mlp.fc1",
211
+ "vision_model.encoder.layers.40.mlp.fc2",
212
+ "vision_model.encoder.layers.41.attn.qkv",
213
+ "vision_model.encoder.layers.41.attn.proj",
214
+ "vision_model.encoder.layers.41.mlp.fc1",
215
+ "vision_model.encoder.layers.41.mlp.fc2",
216
+ "vision_model.encoder.layers.42.attn.qkv",
217
+ "vision_model.encoder.layers.42.attn.proj",
218
+ "vision_model.encoder.layers.42.mlp.fc1",
219
+ "vision_model.encoder.layers.42.mlp.fc2",
220
+ "vision_model.encoder.layers.43.attn.qkv",
221
+ "vision_model.encoder.layers.43.attn.proj",
222
+ "vision_model.encoder.layers.43.mlp.fc1",
223
+ "vision_model.encoder.layers.43.mlp.fc2",
224
+ "vision_model.encoder.layers.44.attn.qkv",
225
+ "vision_model.encoder.layers.44.attn.proj",
226
+ "vision_model.encoder.layers.44.mlp.fc1",
227
+ "vision_model.encoder.layers.44.mlp.fc2",
228
+ "language_model.lm_head",
229
+ "mlp1.1",
230
+ "mlp1.3"
231
+ ],
232
+ "kv_cache_scheme": null,
233
+ "quant_method": "compressed-tensors",
234
+ "quantization_status": "compressed",
235
+ "version": "0.6.0.20241003"
236
+ },
237
+ "downsample_ratio": 0.5,
238
+ "dynamic_image_size": true,
239
+ "force_image_size": 448,
240
+ "llm_config": {
241
+ "_name_or_path": "Qwen/Qwen2-72B-Instruct",
242
+ "add_cross_attention": false,
243
+ "architectures": [
244
+ "Qwen2ForCausalLM"
245
+ ],
246
+ "attention_bias": true,
247
+ "attention_dropout": 0.0,
248
+ "bad_words_ids": null,
249
+ "begin_suppress_tokens": null,
250
+ "bos_token_id": 151643,
251
+ "chunk_size_feed_forward": 0,
252
+ "cross_attention_hidden_size": null,
253
+ "decoder_start_token_id": null,
254
+ "diversity_penalty": 0.0,
255
+ "do_sample": false,
256
+ "early_stopping": false,
257
+ "encoder_no_repeat_ngram_size": 0,
258
+ "eos_token_id": 151645,
259
+ "exponential_decay_length_penalty": null,
260
+ "finetuning_task": null,
261
+ "forced_bos_token_id": null,
262
+ "forced_eos_token_id": null,
263
+ "hidden_act": "silu",
264
+ "hidden_size": 8192,
265
+ "id2label": {
266
+ "0": "LABEL_0",
267
+ "1": "LABEL_1"
268
+ },
269
+ "initializer_range": 0.02,
270
+ "intermediate_size": 29568,
271
+ "is_decoder": false,
272
+ "is_encoder_decoder": false,
273
+ "label2id": {
274
+ "LABEL_0": 0,
275
+ "LABEL_1": 1
276
+ },
277
+ "length_penalty": 1.0,
278
+ "max_length": 20,
279
+ "max_position_embeddings": 32768,
280
+ "max_window_layers": 28,
281
+ "min_length": 0,
282
+ "mlp_bias": false,
283
+ "model_type": "qwen2",
284
+ "no_repeat_ngram_size": 0,
285
+ "num_attention_heads": 64,
286
+ "num_beam_groups": 1,
287
+ "num_beams": 1,
288
+ "num_hidden_layers": 80,
289
+ "num_key_value_heads": 8,
290
+ "num_return_sequences": 1,
291
+ "output_attentions": false,
292
+ "output_hidden_states": false,
293
+ "output_scores": false,
294
+ "pad_token_id": null,
295
+ "prefix": null,
296
+ "pretraining_tp": 1,
297
+ "problem_type": null,
298
+ "pruned_heads": {},
299
+ "remove_invalid_values": false,
300
+ "repetition_penalty": 1.0,
301
+ "return_dict": true,
302
+ "return_dict_in_generate": false,
303
+ "rms_norm_eps": 1e-06,
304
+ "rope_scaling": {
305
+ "factor": 3.0,
306
+ "rope_type": "dynamic",
307
+ "type": "dynamic"
308
+ },
309
+ "rope_theta": 1000000.0,
310
+ "sep_token_id": null,
311
+ "sliding_window": null,
312
+ "suppress_tokens": null,
313
+ "task_specific_params": null,
314
+ "temperature": 1.0,
315
+ "tf_legacy_loss": false,
316
+ "tie_encoder_decoder": false,
317
+ "tie_word_embeddings": false,
318
+ "tokenizer_class": null,
319
+ "top_k": 1,
320
+ "top_p": 0,
321
+ "torch_dtype": "bfloat16",
322
+ "torchscript": false,
323
+ "transformers_version": "4.45.1",
324
+ "typical_p": 1.0,
325
+ "use_bfloat16": true,
326
+ "use_cache": true,
327
+ "use_sliding_window": false,
328
+ "vocab_size": 152064
329
+ },
330
+ "max_dynamic_patch": 6,
331
+ "min_dynamic_patch": 1,
332
+ "model_type": "NVLM_D",
333
+ "ps_version": "v2",
334
+ "select_layer": -1,
335
+ "template": "chatml",
336
+ "torch_dtype": "bfloat16",
337
+ "transformers_version": null,
338
+ "use_backbone_lora": 0,
339
+ "use_llm_lora": 0,
340
+ "use_thumbnail": true,
341
+ "vision_config": {
342
+ "_name_or_path": "",
343
+ "add_cross_attention": false,
344
+ "architectures": [
345
+ "InternVisionModel"
346
+ ],
347
+ "attention_dropout": 0.0,
348
+ "bad_words_ids": null,
349
+ "begin_suppress_tokens": null,
350
+ "bos_token_id": null,
351
+ "chunk_size_feed_forward": 0,
352
+ "cross_attention_hidden_size": null,
353
+ "decoder_start_token_id": null,
354
+ "diversity_penalty": 0.0,
355
+ "do_sample": false,
356
+ "drop_path_rate": 0.0,
357
+ "dropout": 0.0,
358
+ "early_stopping": false,
359
+ "encoder_no_repeat_ngram_size": 0,
360
+ "eos_token_id": null,
361
+ "exponential_decay_length_penalty": null,
362
+ "finetuning_task": null,
363
+ "forced_bos_token_id": null,
364
+ "forced_eos_token_id": null,
365
+ "hidden_act": "gelu",
366
+ "hidden_size": 3200,
367
+ "id2label": {
368
+ "0": "LABEL_0",
369
+ "1": "LABEL_1"
370
+ },
371
+ "image_size": 448,
372
+ "initializer_factor": 0.1,
373
+ "initializer_range": 1e-10,
374
+ "intermediate_size": 12800,
375
+ "is_decoder": false,
376
+ "is_encoder_decoder": false,
377
+ "label2id": {
378
+ "LABEL_0": 0,
379
+ "LABEL_1": 1
380
+ },
381
+ "layer_norm_eps": 1e-06,
382
+ "length_penalty": 1.0,
383
+ "max_length": 20,
384
+ "min_length": 0,
385
+ "model_type": "intern_vit_6b",
386
+ "no_repeat_ngram_size": 0,
387
+ "norm_type": "rms_norm",
388
+ "num_attention_heads": 25,
389
+ "num_beam_groups": 1,
390
+ "num_beams": 1,
391
+ "num_channels": 3,
392
+ "num_hidden_layers": 45,
393
+ "num_return_sequences": 1,
394
+ "output_attentions": false,
395
+ "output_hidden_states": false,
396
+ "output_scores": false,
397
+ "pad_token_id": null,
398
+ "patch_size": 14,
399
+ "prefix": null,
400
+ "problem_type": null,
401
+ "pruned_heads": {},
402
+ "qk_normalization": true,
403
+ "qkv_bias": false,
404
+ "remove_invalid_values": false,
405
+ "repetition_penalty": 1.0,
406
+ "return_dict": true,
407
+ "return_dict_in_generate": false,
408
+ "sep_token_id": null,
409
+ "suppress_tokens": null,
410
+ "task_specific_params": null,
411
+ "temperature": 1.0,
412
+ "tf_legacy_loss": false,
413
+ "tie_encoder_decoder": false,
414
+ "tie_word_embeddings": true,
415
+ "tokenizer_class": null,
416
+ "top_k": 50,
417
+ "top_p": 1.0,
418
+ "torch_dtype": "bfloat16",
419
+ "torchscript": false,
420
+ "transformers_version": "4.45.1",
421
+ "typical_p": 1.0,
422
+ "use_bfloat16": true,
423
+ "use_flash_attn": false
424
+ }
425
+ }
configuration_intern_vit.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class InternVisionConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
18
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
19
+
20
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21
+ documentation from [`PretrainedConfig`] for more information.
22
+
23
+ Args:
24
+ num_channels (`int`, *optional*, defaults to 3):
25
+ Number of color channels in the input images (e.g., 3 for RGB).
26
+ patch_size (`int`, *optional*, defaults to 14):
27
+ The size (resolution) of each patch.
28
+ image_size (`int`, *optional*, defaults to 224):
29
+ The size (resolution) of each image.
30
+ qkv_bias (`bool`, *optional*, defaults to `False`):
31
+ Whether to add a bias to the queries and values in the self-attention layers.
32
+ hidden_size (`int`, *optional*, defaults to 3200):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_attention_heads (`int`, *optional*, defaults to 25):
35
+ Number of attention heads for each attention layer in the Transformer encoder.
36
+ intermediate_size (`int`, *optional*, defaults to 12800):
37
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
38
+ qk_normalization (`bool`, *optional*, defaults to `True`):
39
+ Whether to normalize the queries and keys in the self-attention layers.
40
+ num_hidden_layers (`int`, *optional*, defaults to 48):
41
+ Number of hidden layers in the Transformer encoder.
42
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
43
+ Whether to use flash attention mechanism.
44
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
45
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
46
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
48
+ The epsilon used by the layer normalization layers.
49
+ dropout (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
52
+ Dropout rate for stochastic depth.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ initializer_factor (`float`, *optional*, defaults to 0.1):
58
+ A factor for layer scale.
59
+ """
60
+
61
+ model_type = 'intern_vit_6b'
62
+
63
+ def __init__(
64
+ self,
65
+ num_channels=3,
66
+ patch_size=14,
67
+ image_size=224,
68
+ qkv_bias=False,
69
+ hidden_size=3200,
70
+ num_attention_heads=25,
71
+ intermediate_size=12800,
72
+ qk_normalization=True,
73
+ num_hidden_layers=48,
74
+ use_flash_attn=True,
75
+ hidden_act='gelu',
76
+ norm_type='rms_norm',
77
+ layer_norm_eps=1e-6,
78
+ dropout=0.0,
79
+ drop_path_rate=0.0,
80
+ attention_dropout=0.0,
81
+ initializer_range=0.02,
82
+ initializer_factor=0.1,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+
87
+ self.hidden_size = hidden_size
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.drop_path_rate = drop_path_rate
91
+ self.num_hidden_layers = num_hidden_layers
92
+ self.num_attention_heads = num_attention_heads
93
+ self.num_channels = num_channels
94
+ self.patch_size = patch_size
95
+ self.image_size = image_size
96
+ self.initializer_range = initializer_range
97
+ self.initializer_factor = initializer_factor
98
+ self.attention_dropout = attention_dropout
99
+ self.layer_norm_eps = layer_norm_eps
100
+ self.hidden_act = hidden_act
101
+ self.norm_type = norm_type
102
+ self.qkv_bias = qkv_bias
103
+ self.qk_normalization = qk_normalization
104
+ self.use_flash_attn = use_flash_attn
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
108
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
109
+
110
+ if 'vision_config' in config_dict:
111
+ config_dict = config_dict['vision_config']
112
+
113
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
114
+ logger.warning(
115
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
116
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
117
+ )
118
+
119
+ return cls.from_dict(config_dict, **kwargs)
configuration_nvlm_d.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B under MIT License
3
+ # LICENSE is in incl_licenses directory.
4
+ # --------------------------------------------------------
5
+
6
+ import copy
7
+
8
+ from transformers import AutoConfig, Qwen2Config
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ from .configuration_intern_vit import InternVisionConfig
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+
17
+ class NVLM_D_Config(PretrainedConfig):
18
+ model_type = 'NVLM_D'
19
+ is_composition = True
20
+
21
+ def __init__(
22
+ self,
23
+ vision_config=None,
24
+ llm_config=None,
25
+ use_backbone_lora=0,
26
+ use_llm_lora=0,
27
+ select_layer=-1,
28
+ force_image_size=None,
29
+ downsample_ratio=0.5,
30
+ template=None,
31
+ dynamic_image_size=False,
32
+ use_thumbnail=False,
33
+ ps_version='v1',
34
+ min_dynamic_patch=1,
35
+ max_dynamic_patch=6,
36
+ **kwargs
37
+ ):
38
+ super().__init__(**kwargs)
39
+
40
+ # Handle vision_config initialization
41
+ if vision_config is None:
42
+ vision_config = {}
43
+ logger.info('vision_config is None. Initializing InternVisionConfig with default values.')
44
+
45
+ # Handle llm_config initialization
46
+ if llm_config is None:
47
+ llm_config = {}
48
+ logger.info('llm_config is None. Initializing LLM Config with default values.')
49
+
50
+ self.vision_config = InternVisionConfig(**vision_config)
51
+
52
+ # Check for supported architecture
53
+ if llm_config.get('architectures', [None])[0] == 'Qwen2ForCausalLM':
54
+ self.llm_config = Qwen2Config(**llm_config)
55
+ else:
56
+ raise ValueError(f"Unsupported architecture: {llm_config.get('architectures', [None])[0]}")
57
+
58
+ # Assign configuration values
59
+ self.use_backbone_lora = use_backbone_lora
60
+ self.use_llm_lora = use_llm_lora
61
+ self.select_layer = select_layer
62
+ self.force_image_size = force_image_size
63
+ self.downsample_ratio = downsample_ratio
64
+ self.template = template
65
+ self.dynamic_image_size = dynamic_image_size
66
+ self.use_thumbnail = use_thumbnail
67
+ self.ps_version = ps_version # Pixel shuffle version
68
+ self.min_dynamic_patch = min_dynamic_patch
69
+ self.max_dynamic_patch = max_dynamic_patch
70
+
71
+ # Log important parameters
72
+ logger.info(f'vision_select_layer: {self.select_layer}')
73
+ logger.info(f'ps_version: {self.ps_version}')
74
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
75
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
76
+
77
+ def to_dict(self):
78
+ """
79
+ Serializes this instance to a Python dictionary. Overrides the default `PretrainedConfig.to_dict`.
80
+
81
+ Returns:
82
+ Dict[str, Any]: Dictionary of all the attributes that make up this configuration instance.
83
+ """
84
+ output = copy.deepcopy(self.__dict__)
85
+ output['vision_config'] = self.vision_config.to_dict()
86
+ output['llm_config'] = self.llm_config.to_dict()
87
+ output['model_type'] = self.model_type
88
+ output['use_backbone_lora'] = self.use_backbone_lora
89
+ output['use_llm_lora'] = self.use_llm_lora
90
+ output['select_layer'] = self.select_layer
91
+ output['force_image_size'] = self.force_image_size
92
+ output['downsample_ratio'] = self.downsample_ratio
93
+ output['template'] = self.template
94
+ output['dynamic_image_size'] = self.dynamic_image_size
95
+ output['use_thumbnail'] = self.use_thumbnail
96
+ output['ps_version'] = self.ps_version
97
+ output['min_dynamic_patch'] = self.min_dynamic_patch
98
+ output['max_dynamic_patch'] = self.max_dynamic_patch
99
+
100
+ return output
conversation.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adapted from https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py under the Apache License 2.0.
3
+ LICENSE is in incl_licenses directory.
4
+
5
+ Conversation prompt templates.
6
+
7
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
8
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
9
+ """
10
+
11
+ import dataclasses
12
+ from enum import IntEnum, auto
13
+ from typing import Any, Dict, List, Tuple, Union
14
+
15
+
16
+ class SeparatorStyle(IntEnum):
17
+ """Separator styles."""
18
+
19
+ ADD_COLON_SINGLE = auto()
20
+ ADD_COLON_TWO = auto()
21
+ ADD_COLON_SPACE_SINGLE = auto()
22
+ NO_COLON_SINGLE = auto()
23
+ NO_COLON_TWO = auto()
24
+ ADD_NEW_LINE_SINGLE = auto()
25
+ LLAMA2 = auto()
26
+ CHATGLM = auto()
27
+ CHATML = auto()
28
+ CHATINTERN = auto()
29
+ DOLLY = auto()
30
+ RWKV = auto()
31
+ PHOENIX = auto()
32
+ ROBIN = auto()
33
+ FALCON_CHAT = auto()
34
+ CHATGLM3 = auto()
35
+ INTERNVL_ZH = auto()
36
+ MPT = auto()
37
+
38
+
39
+ @dataclasses.dataclass
40
+ class Conversation:
41
+ """A class that manages prompt templates and keeps all conversation history."""
42
+
43
+ # The name of this template
44
+ name: str
45
+ # The template of the system prompt
46
+ system_template: str = '{system_message}'
47
+ # The system message
48
+ system_message: str = ''
49
+ # The names of two roles
50
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
51
+ # All messages. Each item is (role, message).
52
+ messages: List[List[str]] = ()
53
+ # The number of few shot examples
54
+ offset: int = 0
55
+ # The separator style and configurations
56
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
57
+ sep: str = '\n'
58
+ sep2: str = None
59
+ # Stop criteria (the default one is EOS token)
60
+ stop_str: Union[str, List[str]] = None
61
+ # Stops generation if meeting any token in this list
62
+ stop_token_ids: List[int] = None
63
+
64
+ def get_prompt(self) -> str:
65
+ """Get the prompt for generation."""
66
+ system_prompt = self.system_template.format(system_message=self.system_message)
67
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
68
+ ret = system_prompt + self.sep
69
+ for role, message in self.messages:
70
+ if message:
71
+ ret += role + ': ' + message + self.sep
72
+ else:
73
+ ret += role + ':'
74
+ return ret
75
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
76
+ seps = [self.sep, self.sep2]
77
+ ret = system_prompt + seps[0]
78
+ for i, (role, message) in enumerate(self.messages):
79
+ if message:
80
+ ret += role + ': ' + message + seps[i % 2]
81
+ else:
82
+ ret += role + ':'
83
+ return ret
84
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
85
+ ret = system_prompt + self.sep
86
+ for role, message in self.messages:
87
+ if message:
88
+ ret += role + ': ' + message + self.sep
89
+ else:
90
+ ret += role + ': ' # must be end with a space
91
+ return ret
92
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
93
+ ret = '' if system_prompt == '' else system_prompt + self.sep
94
+ for role, message in self.messages:
95
+ if message:
96
+ ret += role + '\n' + message + self.sep
97
+ else:
98
+ ret += role + '\n'
99
+ return ret
100
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
101
+ ret = system_prompt
102
+ for role, message in self.messages:
103
+ if message:
104
+ ret += role + message + self.sep
105
+ else:
106
+ ret += role
107
+ return ret
108
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
109
+ seps = [self.sep, self.sep2]
110
+ ret = system_prompt
111
+ for i, (role, message) in enumerate(self.messages):
112
+ if message:
113
+ ret += role + message + seps[i % 2]
114
+ else:
115
+ ret += role
116
+ return ret
117
+ elif self.sep_style == SeparatorStyle.RWKV:
118
+ ret = system_prompt
119
+ for i, (role, message) in enumerate(self.messages):
120
+ if message:
121
+ ret += (
122
+ role
123
+ + ': '
124
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
125
+ )
126
+ ret += '\n\n'
127
+ else:
128
+ ret += role + ':'
129
+ return ret
130
+ elif self.sep_style == SeparatorStyle.LLAMA2:
131
+ seps = [self.sep, self.sep2]
132
+ if self.system_message:
133
+ ret = system_prompt
134
+ else:
135
+ ret = '[INST] '
136
+ for i, (role, message) in enumerate(self.messages):
137
+ tag = self.roles[i % 2]
138
+ if message:
139
+ if i == 0:
140
+ ret += message + ' '
141
+ else:
142
+ ret += tag + ' ' + message + seps[i % 2]
143
+ else:
144
+ ret += tag
145
+ return ret
146
+ elif self.sep_style == SeparatorStyle.CHATGLM:
147
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
148
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
149
+ round_add_n = 1 if self.name == 'chatglm2' else 0
150
+ if system_prompt:
151
+ ret = system_prompt + self.sep
152
+ else:
153
+ ret = ''
154
+
155
+ for i, (role, message) in enumerate(self.messages):
156
+ if i % 2 == 0:
157
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
158
+
159
+ if message:
160
+ ret += f'{role}:{message}{self.sep}'
161
+ else:
162
+ ret += f'{role}:'
163
+ return ret
164
+ elif self.sep_style == SeparatorStyle.CHATML:
165
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
166
+ for role, message in self.messages:
167
+ if message:
168
+ ret += role + '\n' + message + self.sep + '\n'
169
+ else:
170
+ ret += role + '\n'
171
+ return ret
172
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
173
+ ret = ''
174
+ if self.system_message:
175
+ ret += system_prompt
176
+ for role, message in self.messages:
177
+ if message:
178
+ ret += role + '\n' + ' ' + message
179
+ else:
180
+ ret += role
181
+ return ret
182
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
183
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
184
+ seps = [self.sep, self.sep2]
185
+ ret = system_prompt
186
+ for i, (role, message) in enumerate(self.messages):
187
+ # if i % 2 == 0:
188
+ # ret += "<s>"
189
+ if message:
190
+ ret += role + ':' + message + seps[i % 2] + '\n'
191
+ else:
192
+ ret += role + ':'
193
+ return ret
194
+ elif self.sep_style == SeparatorStyle.DOLLY:
195
+ seps = [self.sep, self.sep2]
196
+ ret = system_prompt
197
+ for i, (role, message) in enumerate(self.messages):
198
+ if message:
199
+ ret += role + ':\n' + message + seps[i % 2]
200
+ if i % 2 == 1:
201
+ ret += '\n\n'
202
+ else:
203
+ ret += role + ':\n'
204
+ return ret
205
+ elif self.sep_style == SeparatorStyle.PHOENIX:
206
+ ret = system_prompt
207
+ for role, message in self.messages:
208
+ if message:
209
+ ret += role + ': ' + '<s>' + message + '</s>'
210
+ else:
211
+ ret += role + ': ' + '<s>'
212
+ return ret
213
+ elif self.sep_style == SeparatorStyle.ROBIN:
214
+ ret = system_prompt + self.sep
215
+ for role, message in self.messages:
216
+ if message:
217
+ ret += role + ':\n' + message + self.sep
218
+ else:
219
+ ret += role + ':\n'
220
+ return ret
221
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
222
+ ret = ''
223
+ if self.system_message:
224
+ ret += system_prompt + self.sep
225
+ for role, message in self.messages:
226
+ if message:
227
+ ret += role + ': ' + message + self.sep
228
+ else:
229
+ ret += role + ':'
230
+
231
+ return ret
232
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
233
+ seps = [self.sep, self.sep2]
234
+ ret = self.system_message + seps[0]
235
+ for i, (role, message) in enumerate(self.messages):
236
+ if message:
237
+ ret += role + ': ' + message + seps[i % 2]
238
+ else:
239
+ ret += role + ':'
240
+ return ret
241
+ elif self.sep_style == SeparatorStyle.MPT:
242
+ ret = system_prompt + self.sep
243
+ for role, message in self.messages:
244
+ if message:
245
+ if type(message) is tuple:
246
+ message, _, _ = message
247
+ ret += role + message + self.sep
248
+ else:
249
+ ret += role
250
+ return ret
251
+ else:
252
+ raise ValueError(f'Invalid style: {self.sep_style}')
253
+
254
+ def set_system_message(self, system_message: str):
255
+ """Set the system message."""
256
+ self.system_message = system_message
257
+
258
+ def append_message(self, role: str, message: str):
259
+ """Append a new message."""
260
+ self.messages.append([role, message])
261
+
262
+ def update_last_message(self, message: str):
263
+ """Update the last output.
264
+
265
+ The last message is typically set to be None when constructing the prompt,
266
+ so we need to update it in-place after getting the response from a model.
267
+ """
268
+ self.messages[-1][1] = message
269
+
270
+ def to_gradio_chatbot(self):
271
+ """Convert the conversation to gradio chatbot format."""
272
+ ret = []
273
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
274
+ if i % 2 == 0:
275
+ ret.append([msg, None])
276
+ else:
277
+ ret[-1][-1] = msg
278
+ return ret
279
+
280
+ def to_openai_api_messages(self):
281
+ """Convert the conversation to OpenAI chat completion format."""
282
+ ret = [{'role': 'system', 'content': self.system_message}]
283
+
284
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
285
+ if i % 2 == 0:
286
+ ret.append({'role': 'user', 'content': msg})
287
+ else:
288
+ if msg is not None:
289
+ ret.append({'role': 'assistant', 'content': msg})
290
+ return ret
291
+
292
+ def copy(self):
293
+ return Conversation(
294
+ name=self.name,
295
+ system_template=self.system_template,
296
+ system_message=self.system_message,
297
+ roles=self.roles,
298
+ messages=[[x, y] for x, y in self.messages],
299
+ offset=self.offset,
300
+ sep_style=self.sep_style,
301
+ sep=self.sep,
302
+ sep2=self.sep2,
303
+ stop_str=self.stop_str,
304
+ stop_token_ids=self.stop_token_ids,
305
+ )
306
+
307
+ def dict(self):
308
+ return {
309
+ 'template_name': self.name,
310
+ 'system_message': self.system_message,
311
+ 'roles': self.roles,
312
+ 'messages': self.messages,
313
+ 'offset': self.offset,
314
+ }
315
+
316
+
317
+ # A global registry for all conversation templates
318
+ conv_templates: Dict[str, Conversation] = {}
319
+
320
+
321
+ def register_conv_template(template: Conversation, override: bool = False):
322
+ """Register a new conversation template."""
323
+ if not override:
324
+ assert (
325
+ template.name not in conv_templates
326
+ ), f'{template.name} has been registered.'
327
+
328
+ conv_templates[template.name] = template
329
+
330
+
331
+ def get_conv_template(name: str) -> Conversation:
332
+ """Get a conversation template."""
333
+ return conv_templates[name].copy()
334
+
335
+
336
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
337
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
338
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
339
+ # Therefore, they are completely equivalent during inference.
340
+
341
+ register_conv_template(
342
+ Conversation(
343
+ name='chatml',
344
+ system_template='<|im_start|>system\n{system_message}',
345
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
346
+ system_message='Answer the questions.',
347
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
348
+ sep_style=SeparatorStyle.MPT,
349
+ sep='<|im_end|>',
350
+ stop_token_ids=[
351
+ 2,
352
+ 92543,
353
+ 92542
354
+ ]
355
+ )
356
+ )
357
+
358
+
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.45.1"
4
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e2bd80c8dedc4927ceed2754d35a5febd05d8834ab108bcbb02e31afd151bf1
3
+ size 4953261920
model-00002-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2975aba1547c1af23facf8df395aa3f957609c5e9edf0fd7b95c15ac2c3511cf
3
+ size 4919977416
model-00003-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc6ec79ecfe123596af81b211070a34d73927cb12677051cf4f12863d61ee3cd
3
+ size 4874646440
model-00004-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6687e875669d2e986d1f61e714e182c94f776ac9489440616198628b6ec8449e
3
+ size 4873987416
model-00005-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d5f34fba80c1599f1ad4d8b0d1a0241d23d72f5c362252ab0a52a1ef30fa0784
3
+ size 4782750936
model-00006-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9a5af27a96c94f0ec949a854bb62c28e5404508613f9b83035b0ed6024a6fce
3
+ size 4873987512
model-00007-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6eecb57659eedc24c56e76f26ae1afc5e7cc8412aff95162ab9e30429ed44667
3
+ size 4782751024
model-00008-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b042758b202d72a62db0c645fa28942c437b634b426a005bee3575cf3b8a7c6d
3
+ size 4873987512
model-00009-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0bff41cf53861c55438eb816aaa8cecd556fa9e131e112e4f99b5a3c0d860ac8
3
+ size 4782751024
model-00010-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e470950b32e9683fd090d1e485c4c4b1439e39d3dfe50bb16e93c7b61b3be4fe
3
+ size 4873987512
model-00011-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c14f6355d8ea6026266b67d43da52df48132981f68556392112450a14e8c1868
3
+ size 4782751024
model-00012-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70b16078d558450a99250b7e4cdfc1d7ee9104a6b9ceaba35fefb3ac9967398c
3
+ size 4873987512
model-00013-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0511c9687245031693d53e5531abb78bdd4a1bc5c04097c71b749c4534c29ac
3
+ size 4782751024
model-00014-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f6712208789ad3ef13c1f5ac83d5a4001256346feb540c248618debad9ed98c
3
+ size 4873987512
model-00015-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20f8a3396d5b9ceec98aab8bb89fc32162ad3144a997ba45ca00009e7f1d9e65
3
+ size 4782751024
model-00016-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a42b31b8468948af610a7a77fd7ff7090624b5b9d1e0f63873cb168064390aa6
3
+ size 4873987512
model-00017-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdde2ad65cf2280579dc46a0e6c4f71a2c4f2716a75208b3d4840b9e337eee4a
3
+ size 4782751024
model-00018-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7aa66665c80bae6fb51895394eeccf45083517826341249d75ef160c74ccfa42
3
+ size 4974087056
model-00019-of-00019.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50fb62d46a9dfd2491c867d542f4fcb09fac4186ada0104c0d42e56bacc35368
3
+ size 1241383128
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_intern_vit.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B under MIT License
3
+ # LICENSE is in incl_licenses directory.
4
+ # --------------------------------------------------------
5
+
6
+
7
+ from typing import Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint
12
+ from einops import rearrange
13
+ from timm.models.layers import DropPath
14
+ from torch import nn
15
+ from transformers.activations import ACT2FN
16
+ from transformers.modeling_outputs import (BaseModelOutput,
17
+ BaseModelOutputWithPooling)
18
+ from transformers.modeling_utils import PreTrainedModel
19
+ from transformers.utils import logging
20
+
21
+ from .configuration_intern_vit import InternVisionConfig
22
+
23
+ has_flash_attn = False
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ """
29
+ The following code is adapted from the
30
+ https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B/blob/main/modeling_intern_vit.py repository
31
+
32
+ We added additional dummy heads to the original num of heads to make the number of heads divisible by 8
33
+ (tensor model parallel size) while having the same output as InternVIT.
34
+ We also turn off flash attn to have deterministic results.
35
+ """
36
+ class InternRMSNorm(nn.Module):
37
+ def __init__(self, hidden_size, eps=1e-6):
38
+ super().__init__()
39
+ self.weight = nn.Parameter(torch.ones(hidden_size))
40
+ self.variance_epsilon = eps
41
+
42
+ def forward(self, hidden_states, var=None):
43
+ input_dtype = hidden_states.dtype
44
+ hidden_states = hidden_states.to(torch.float32)
45
+ if var is None:
46
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
47
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
48
+ else:
49
+ hidden_states = hidden_states * torch.rsqrt(var + self.variance_epsilon)
50
+
51
+ return hidden_states.to(input_dtype) * self.weight
52
+
53
+
54
+ class InternVisionEmbeddings(nn.Module):
55
+ def __init__(self, config: InternVisionConfig):
56
+ super().__init__()
57
+ self.config = config
58
+ self.embed_dim = config.hidden_size
59
+ self.image_size = config.image_size
60
+ self.patch_size = config.patch_size
61
+
62
+ self.class_embedding = nn.Parameter(
63
+ torch.randn(1, 1, self.embed_dim),
64
+ )
65
+
66
+ self.patch_embedding = nn.Conv2d(
67
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
68
+ )
69
+
70
+ self.num_patches = (self.image_size // self.patch_size) ** 2
71
+ self.num_positions = self.num_patches + 1
72
+
73
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
74
+
75
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
76
+ batch_size = pixel_values.shape[0]
77
+ target_dtype = self.patch_embedding.weight.dtype
78
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
79
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
80
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
81
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
82
+ embeddings = embeddings + self.position_embedding.to(target_dtype)
83
+ return embeddings
84
+
85
+
86
+ class InternAttention(nn.Module):
87
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
88
+
89
+ def __init__(self, config: InternVisionConfig):
90
+ super().__init__()
91
+ self.config = config
92
+ self.embed_dim = config.hidden_size
93
+ self.num_heads = config.num_attention_heads
94
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
95
+ if config.use_flash_attn and not has_flash_attn:
96
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
97
+
98
+ self.head_dim = self.embed_dim // self.num_heads
99
+ if self.head_dim * self.num_heads != self.embed_dim:
100
+ raise ValueError(
101
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
102
+ f' {self.num_heads}).'
103
+ )
104
+
105
+ self.scale = self.head_dim ** -0.5
106
+ # We added additional dummy heads to the original num of heads to make the number of heads divisible by 8.
107
+ self.num_dummy_heads = 7
108
+ self.dummy_dim = (self.num_dummy_heads + self.num_heads) * self.head_dim
109
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.dummy_dim, bias=config.qkv_bias)
110
+ self.attn_drop = nn.Dropout(config.attention_dropout)
111
+ self.proj_drop = nn.Dropout(config.dropout)
112
+
113
+ self.qk_normalization = config.qk_normalization
114
+
115
+ if self.qk_normalization:
116
+ self.q_norm = InternRMSNorm(self.dummy_dim, eps=config.layer_norm_eps)
117
+ self.k_norm = InternRMSNorm(self.dummy_dim, eps=config.layer_norm_eps)
118
+
119
+ if self.use_flash_attn:
120
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
121
+ self.proj = nn.Linear(self.dummy_dim, self.embed_dim)
122
+
123
+ def _naive_attn(self, x):
124
+ B, N, C = x.shape
125
+
126
+ qkv = torch.matmul(x, self.qkv.weight.t()).reshape(B, N, 3, self.num_dummy_heads + self.num_heads,
127
+ C // self.num_heads).permute(2, 0, 3, 1, 4)
128
+
129
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
130
+
131
+ if self.qk_normalization:
132
+ B_, H_, N_, D_ = q.shape
133
+ q_var = q.transpose(1, 2).flatten(-2, -1)[:, :, :self.embed_dim].float().pow(2).sum(-1,
134
+ keepdim=True) / self.embed_dim
135
+ k_var = k.transpose(1, 2).flatten(-2, -1)[:, :, :self.embed_dim].float().pow(2).sum(-1,
136
+ keepdim=True) / self.embed_dim
137
+
138
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1), var=q_var).view(B_, N_, H_, D_).transpose(1, 2)
139
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1), var=k_var).view(B_, N_, H_, D_).transpose(1, 2)
140
+
141
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
142
+ attn = attn.softmax(dim=-1)
143
+
144
+ attn = self.attn_drop(attn)
145
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
146
+
147
+ x = torch.matmul(x, self.proj.weight.t()) + self.proj.bias
148
+ x = self.proj_drop(x)
149
+ return x
150
+
151
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
152
+ qkv = self.qkv(x)
153
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
154
+
155
+ if self.qk_normalization:
156
+ q, k, v = qkv.unbind(2)
157
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
158
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
159
+ qkv = torch.stack([q, k, v], dim=2)
160
+
161
+ context, _ = self.inner_attn(
162
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
163
+ )
164
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
165
+ outs = self.proj_drop(outs)
166
+ return outs
167
+
168
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
169
+ x = self._naive_attn(hidden_states)
170
+ return x
171
+
172
+
173
+ class InternMLP(nn.Module):
174
+ def __init__(self, config: InternVisionConfig):
175
+ super().__init__()
176
+ self.config = config
177
+ self.act = ACT2FN[config.hidden_act]
178
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
179
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
180
+
181
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
182
+ hidden_states = torch.matmul(hidden_states, self.fc1.weight.t()) + self.fc1.bias
183
+ hidden_states = self.act(hidden_states)
184
+ hidden_states = torch.matmul(hidden_states, self.fc2.weight.t()) + self.fc2.bias
185
+ return hidden_states
186
+
187
+
188
+ class InternVisionEncoderLayer(nn.Module):
189
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
190
+ super().__init__()
191
+ self.embed_dim = config.hidden_size
192
+ self.intermediate_size = config.intermediate_size
193
+ self.norm_type = config.norm_type
194
+
195
+ self.attn = InternAttention(config)
196
+ self.mlp = InternMLP(config)
197
+ self.norm1 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
198
+ self.norm2 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
199
+
200
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
201
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
202
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
203
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
204
+
205
+ def forward(
206
+ self,
207
+ hidden_states: torch.Tensor,
208
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
209
+ """
210
+ Args:
211
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
212
+ """
213
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
214
+
215
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
216
+
217
+ return hidden_states
218
+
219
+
220
+ class InternVisionEncoder(nn.Module):
221
+ """
222
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
223
+ [`InternEncoderLayer`].
224
+
225
+ Args:
226
+ config (`InternConfig`):
227
+ The corresponding vision configuration for the `InternEncoder`.
228
+ """
229
+
230
+ def __init__(self, config: InternVisionConfig):
231
+ super().__init__()
232
+ self.config = config
233
+ # stochastic depth decay rule
234
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
235
+ self.layers = nn.ModuleList([
236
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
237
+ self.gradient_checkpointing = True
238
+
239
+ def forward(
240
+ self,
241
+ inputs_embeds,
242
+ output_hidden_states: Optional[bool] = None,
243
+ return_dict: Optional[bool] = None,
244
+ ) -> Union[Tuple, BaseModelOutput]:
245
+ r"""
246
+ Args:
247
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
248
+ Embedded representation of the inputs. Should be float, not int tokens.
249
+ output_hidden_states (`bool`, *optional*):
250
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
251
+ for more detail.
252
+ return_dict (`bool`, *optional*):
253
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
254
+ """
255
+ output_hidden_states = (
256
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
257
+ )
258
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
259
+
260
+ encoder_states = () if output_hidden_states else None
261
+ hidden_states = inputs_embeds
262
+
263
+ for idx, encoder_layer in enumerate(self.layers):
264
+ if output_hidden_states:
265
+ encoder_states = encoder_states + (hidden_states,)
266
+ if self.gradient_checkpointing and self.training:
267
+ layer_outputs = torch.utils.checkpoint.checkpoint(
268
+ encoder_layer,
269
+ hidden_states)
270
+ else:
271
+ layer_outputs = encoder_layer(
272
+ hidden_states,
273
+ )
274
+ hidden_states = layer_outputs
275
+
276
+ if output_hidden_states:
277
+ encoder_states = encoder_states + (hidden_states,)
278
+
279
+ if not return_dict:
280
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
281
+ return BaseModelOutput(
282
+ last_hidden_state=hidden_states, hidden_states=encoder_states
283
+ )
284
+
285
+
286
+ class InternVisionModel(PreTrainedModel):
287
+ main_input_name = 'pixel_values'
288
+ _supports_flash_attn_2 = True
289
+ config_class = InternVisionConfig
290
+ _no_split_modules = ['InternVisionEncoderLayer']
291
+
292
+ def __init__(self, config: InternVisionConfig):
293
+ super().__init__(config)
294
+ self.config = config
295
+
296
+ self.embeddings = InternVisionEmbeddings(config)
297
+ self.encoder = InternVisionEncoder(config)
298
+
299
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
300
+ pos_emb = self.embeddings.position_embedding
301
+ _, num_positions, embed_dim = pos_emb.shape
302
+ cls_emb = pos_emb[:, :1, :]
303
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
304
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
305
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
306
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
307
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
308
+ self.embeddings.image_size = new_size
309
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
310
+
311
+ def get_input_embeddings(self):
312
+ return self.embeddings
313
+
314
+ def forward(
315
+ self,
316
+ pixel_values: Optional[torch.FloatTensor] = None,
317
+ output_hidden_states: Optional[bool] = None,
318
+ return_dict: Optional[bool] = None,
319
+ pixel_embeds: Optional[torch.FloatTensor] = None,
320
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
321
+ output_hidden_states = (
322
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
323
+ )
324
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
325
+
326
+ if pixel_values is None and pixel_embeds is None:
327
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
328
+
329
+ if pixel_embeds is not None:
330
+ hidden_states = pixel_embeds
331
+ else:
332
+ if len(pixel_values.shape) == 4:
333
+ hidden_states = self.embeddings(pixel_values)
334
+ else:
335
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
336
+ encoder_outputs = self.encoder(
337
+ inputs_embeds=hidden_states,
338
+ output_hidden_states=output_hidden_states,
339
+ return_dict=return_dict,
340
+ )
341
+
342
+ last_hidden_state = encoder_outputs.last_hidden_state
343
+
344
+ pooled_output = last_hidden_state[:, 0, :]
345
+
346
+ if not return_dict:
347
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
348
+
349
+ return BaseModelOutputWithPooling(
350
+ last_hidden_state=last_hidden_state,
351
+ pooler_output=pooled_output,
352
+ hidden_states=encoder_outputs.hidden_states,
353
+ attentions=encoder_outputs.attentions,
354
+ )
modeling_nvlm_d.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B under MIT License
3
+ # LICENSE is in incl_licenses directory.
4
+ # --------------------------------------------------------
5
+
6
+
7
+ import warnings
8
+ from typing import Any, List, Optional, Tuple, Union
9
+
10
+ import torch.utils.checkpoint
11
+ import transformers
12
+ from torch import nn
13
+ from torch.nn import CrossEntropyLoss
14
+ from transformers import AutoModel, GenerationConfig, Qwen2ForCausalLM
15
+ from transformers.modeling_outputs import CausalLMOutputWithPast
16
+ from transformers.modeling_utils import PreTrainedModel
17
+ from transformers.utils import ModelOutput, logging
18
+
19
+ from .configuration_nvlm_d import NVLM_D_Config
20
+ from .conversation import get_conv_template
21
+ from .modeling_intern_vit import InternVisionModel, has_flash_attn
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ """
27
+ The following code is adapted from the
28
+ https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B/blob/main/modeling_internvl_chat.py repository
29
+
30
+ The chat function is adapted to handle NVLM 1-D tile-tagging design for dynamic high-resolution images.
31
+ """
32
+ def version_cmp(v1, v2, op='eq'):
33
+ import operator
34
+
35
+ from packaging import version
36
+ op_func = getattr(operator, op)
37
+ return op_func(version.parse(v1), version.parse(v2))
38
+
39
+
40
+ class NVLM_D_Model(PreTrainedModel):
41
+ config_class = NVLM_D_Config
42
+ main_input_name = 'pixel_values'
43
+ _supports_flash_attn_2 = True
44
+ _no_split_modules = ['InternVisionModel', 'Qwen2DecoderLayer']
45
+
46
+ def __init__(self, config: NVLM_D_Config, vision_model=None, language_model=None, use_flash_attn=True):
47
+ super().__init__(config)
48
+
49
+ assert version_cmp(transformers.__version__, '4.36.2', 'ge')
50
+ image_size = config.force_image_size or config.vision_config.image_size
51
+ patch_size = config.vision_config.patch_size
52
+ self.patch_size = patch_size
53
+ self.select_layer = config.select_layer
54
+ self.template = config.template
55
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
56
+ self.downsample_ratio = config.downsample_ratio
57
+ self.ps_version = config.ps_version
58
+ use_flash_attn = use_flash_attn if has_flash_attn else False
59
+ config.vision_config.use_flash_attn = True if use_flash_attn else False
60
+ config.llm_config._attn_implementation = 'flash_attention_2' if use_flash_attn else 'eager'
61
+
62
+ logger.info(f'num_image_token: {self.num_image_token}')
63
+ logger.info(f'ps_version: {self.ps_version}')
64
+ if vision_model is not None:
65
+ self.vision_model = vision_model
66
+ else:
67
+ self.vision_model = InternVisionModel(config.vision_config)
68
+ if language_model is not None:
69
+ self.language_model = language_model
70
+ else:
71
+ if config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
72
+ self.language_model = Qwen2ForCausalLM(config.llm_config)
73
+ else:
74
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
75
+
76
+ vit_hidden_size = config.vision_config.hidden_size
77
+ llm_intermediate_size = config.llm_config.intermediate_size
78
+ llm_hidden_size = config.llm_config.hidden_size
79
+
80
+ self.mlp1 = nn.Sequential(
81
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
82
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_intermediate_size, bias=False),
83
+ nn.GELU(),
84
+ nn.Linear(llm_intermediate_size, llm_hidden_size, bias=False)
85
+ )
86
+
87
+ self.img_context_token_id = None
88
+ self.conv_template = get_conv_template(self.template)
89
+ self.system_message = self.conv_template.system_message
90
+
91
+ def forward(
92
+ self,
93
+ pixel_values: torch.FloatTensor,
94
+ input_ids: torch.LongTensor = None,
95
+ attention_mask: Optional[torch.Tensor] = None,
96
+ position_ids: Optional[torch.LongTensor] = None,
97
+ image_flags: Optional[torch.LongTensor] = None,
98
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
99
+ labels: Optional[torch.LongTensor] = None,
100
+ use_cache: Optional[bool] = None,
101
+ output_attentions: Optional[bool] = None,
102
+ output_hidden_states: Optional[bool] = None,
103
+ return_dict: Optional[bool] = None,
104
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
105
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
106
+
107
+ image_flags = image_flags.squeeze(-1)
108
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
109
+
110
+ vit_embeds = self.extract_feature(pixel_values)
111
+ vit_embeds = vit_embeds[image_flags == 1]
112
+ vit_batch_size = pixel_values.shape[0]
113
+
114
+ B, N, C = input_embeds.shape
115
+ input_embeds = input_embeds.reshape(B * N, C)
116
+
117
+ if torch.distributed.get_rank() == 0:
118
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
119
+
120
+ input_ids = input_ids.reshape(B * N)
121
+ selected = (input_ids == self.img_context_token_id)
122
+ try:
123
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
124
+ except Exception as e:
125
+ vit_embeds = vit_embeds.reshape(-1, C)
126
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
127
+ f'vit_embeds.shape={vit_embeds.shape}')
128
+ n_token = selected.sum()
129
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
130
+
131
+ input_embeds = input_embeds.reshape(B, N, C)
132
+
133
+ outputs = self.language_model(
134
+ inputs_embeds=input_embeds,
135
+ attention_mask=attention_mask,
136
+ position_ids=position_ids,
137
+ past_key_values=past_key_values,
138
+ use_cache=use_cache,
139
+ output_attentions=output_attentions,
140
+ output_hidden_states=output_hidden_states,
141
+ return_dict=return_dict,
142
+ )
143
+ logits = outputs.logits
144
+
145
+ loss = None
146
+ if labels is not None:
147
+ # Shift so that tokens < n predict n
148
+ shift_logits = logits[..., :-1, :].contiguous()
149
+ shift_labels = labels[..., 1:].contiguous()
150
+ # Flatten the tokens
151
+ loss_fct = CrossEntropyLoss()
152
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
153
+ shift_labels = shift_labels.view(-1)
154
+ # Enable model parallelism
155
+ shift_labels = shift_labels.to(shift_logits.device)
156
+ loss = loss_fct(shift_logits, shift_labels)
157
+
158
+ if not return_dict:
159
+ output = (logits,) + outputs[1:]
160
+ return (loss,) + output if loss is not None else output
161
+
162
+ return CausalLMOutputWithPast(
163
+ loss=loss,
164
+ logits=logits,
165
+ past_key_values=outputs.past_key_values,
166
+ hidden_states=outputs.hidden_states,
167
+ attentions=outputs.attentions,
168
+ )
169
+
170
+ def pixel_shuffle(self, x, scale_factor=0.5):
171
+ n, w, h, c = x.size()
172
+ # N, W, H, C --> N, W, H * scale, C // scale
173
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
174
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
175
+ x = x.permute(0, 2, 1, 3).contiguous()
176
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
177
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
178
+ int(c / (scale_factor * scale_factor)))
179
+ if self.ps_version == 'v1':
180
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
181
+ 'which results in a transposed image.')
182
+ else:
183
+ x = x.permute(0, 2, 1, 3).contiguous()
184
+ return x
185
+
186
+ def extract_feature(self, pixel_values):
187
+ if self.select_layer == -1:
188
+ vit_embeds = self.vision_model(
189
+ pixel_values=pixel_values,
190
+ output_hidden_states=False,
191
+ return_dict=True).last_hidden_state
192
+ else:
193
+ vit_embeds = self.vision_model(
194
+ pixel_values=pixel_values,
195
+ output_hidden_states=True,
196
+ return_dict=True).hidden_states[self.select_layer]
197
+ vit_embeds = vit_embeds[:, 1:, :]
198
+
199
+ h = w = int(vit_embeds.shape[1] ** 0.5)
200
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
201
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
202
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
203
+ vit_embeds = self.mlp1(vit_embeds)
204
+ return vit_embeds
205
+
206
+
207
+ """
208
+ Adapts the chat function to handle NVLM 1-D tile-tagging design for dynamic high-resolution images.
209
+ Additionally, it supports the following:
210
+ - Chat without a system prompt.
211
+ - Chat without an image prompt.
212
+ """
213
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
214
+ num_patches_list=None, IMG_START_TOKEN='<|vision_start|>', IMG_END_TOKEN='<|vision_end|>',
215
+ IMG_CONTEXT_TOKEN='<|vision_pad|>', verbose=False, visual_features=None):
216
+
217
+ if history is None and pixel_values is not None and '<image>' not in question:
218
+ question = '<image>\n' + question
219
+
220
+ if num_patches_list is None:
221
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
222
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
223
+
224
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
225
+ self.img_context_token_id = img_context_token_id
226
+
227
+ template = get_conv_template(self.template)
228
+ template.system_message = self.system_message
229
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
230
+
231
+ history = [] if history is None else history
232
+ for (old_question, old_answer) in history:
233
+ template.append_message(template.roles[0], old_question)
234
+ template.append_message(template.roles[1], old_answer)
235
+ template.append_message(template.roles[0], question)
236
+ template.append_message(template.roles[1], None)
237
+ query = template.get_prompt()
238
+
239
+ if verbose and pixel_values is not None:
240
+ image_bs = pixel_values.shape[0]
241
+ print(f'dynamic ViT batch size: {image_bs}')
242
+
243
+ for num_patches in num_patches_list:
244
+ tile_pos_identifiers = [f"<tile_{i}>" for i in range(1, num_patches)] + ["<tile_global_thumbnail>"]
245
+ image_tokens = ''
246
+ for tile_pos_identifier in tile_pos_identifiers:
247
+ image_tokens += tile_pos_identifier + IMG_CONTEXT_TOKEN * self.num_image_token
248
+ image_tokens = '<Image>' + image_tokens + '</Image>'
249
+ query = query.replace('<image>', image_tokens, 1)
250
+
251
+ model_inputs = tokenizer(query, return_tensors='pt')
252
+ input_ids = model_inputs['input_ids'].cuda()
253
+ attention_mask = model_inputs['attention_mask'].cuda()
254
+ generation_config['eos_token_id'] = eos_token_id
255
+ generation_output = self.generate(
256
+ pixel_values=pixel_values,
257
+ visual_features=visual_features,
258
+ input_ids=input_ids,
259
+ attention_mask=attention_mask,
260
+ **generation_config
261
+ )
262
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
263
+ response = response.split(template.sep)[0].strip()
264
+ history.append((question, response))
265
+ if return_history:
266
+ return response, history
267
+ else:
268
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
269
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
270
+ if verbose:
271
+ print(query_to_print, response)
272
+ return response
273
+
274
+ def chat_without_sys_prompt(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
275
+ num_patches_list=None, IMG_START_TOKEN='<|vision_start|>', IMG_END_TOKEN='<|vision_end|>',
276
+ IMG_CONTEXT_TOKEN='<|vision_pad|>', verbose=False, visual_features=None):
277
+
278
+ if history is None and pixel_values is not None and '<image>' not in question:
279
+ question = '<image>\n' + question
280
+
281
+ if num_patches_list is None:
282
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
283
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
284
+
285
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
286
+ self.img_context_token_id = img_context_token_id
287
+
288
+ template = get_conv_template(self.template)
289
+ system_prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>" # override dummy system prompt
290
+ template.system_message = system_prompt
291
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
292
+
293
+ history = [] if history is None else history
294
+ for (old_question, old_answer) in history:
295
+ template.append_message(template.roles[0], old_question)
296
+ template.append_message(template.roles[1], old_answer)
297
+ template.append_message(template.roles[0], question)
298
+ template.append_message(template.roles[1], None)
299
+ query = template.get_prompt()
300
+
301
+ if verbose and pixel_values is not None:
302
+ image_bs = pixel_values.shape[0]
303
+ print(f'dynamic ViT batch size: {image_bs}')
304
+
305
+ query = query[len(system_prompt):]
306
+
307
+ for num_patches in num_patches_list:
308
+ tile_pos_identifiers = [f"<tile_{i}>" for i in range(1, num_patches)] + ["<tile_global_thumbnail>"]
309
+ image_tokens = ''
310
+ for tile_pos_identifier in tile_pos_identifiers:
311
+ image_tokens += tile_pos_identifier + IMG_CONTEXT_TOKEN * self.num_image_token
312
+ image_tokens = '<Image>' + image_tokens + '</Image>'
313
+ query = query.replace('<image>', image_tokens, 1)
314
+
315
+ model_inputs = tokenizer(query, return_tensors='pt')
316
+ input_ids = model_inputs['input_ids'].cuda()
317
+ attention_mask = model_inputs['attention_mask'].cuda()
318
+ generation_config['eos_token_id'] = eos_token_id
319
+ generation_output = self.generate(
320
+ pixel_values=pixel_values,
321
+ visual_features=visual_features,
322
+ input_ids=input_ids,
323
+ attention_mask=attention_mask,
324
+ **generation_config
325
+ )
326
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
327
+ response = response.split(template.sep)[0].strip()
328
+ history.append((question, response))
329
+ if return_history:
330
+ return response, history
331
+ else:
332
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
333
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
334
+ if verbose:
335
+ print(query_to_print, response)
336
+ return response
337
+
338
+ def chat_without_chat_prompt(self, tokenizer, pixel_values, question, generation_config,
339
+ num_patches_list=None, IMG_START_TOKEN='<|vision_start|>', IMG_END_TOKEN='<|vision_end|>',
340
+ IMG_CONTEXT_TOKEN='<|vision_pad|>', verbose=False, visual_features=None):
341
+
342
+ if pixel_values is not None and '<image>' not in question:
343
+ question = '<image>\n' + question
344
+
345
+ if num_patches_list is None:
346
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
347
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
348
+
349
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
350
+ self.img_context_token_id = img_context_token_id
351
+
352
+ template = get_conv_template(self.template)
353
+ template.system_message = self.system_message
354
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
355
+
356
+ if verbose and pixel_values is not None:
357
+ image_bs = pixel_values.shape[0]
358
+ print(f'dynamic ViT batch size: {image_bs}')
359
+
360
+ query = question
361
+
362
+ for num_patches in num_patches_list:
363
+ tile_pos_identifiers = [f"<tile_{i}>" for i in range(1, num_patches)] + ["<tile_global_thumbnail>"]
364
+ image_tokens = ''
365
+ for tile_pos_identifier in tile_pos_identifiers:
366
+ image_tokens += tile_pos_identifier + IMG_CONTEXT_TOKEN * self.num_image_token
367
+ image_tokens = '<Image>' + image_tokens + '</Image>'
368
+ query = query.replace('<image>', image_tokens, 1)
369
+
370
+ model_inputs = tokenizer(query, return_tensors='pt')
371
+ input_ids = model_inputs['input_ids'].cuda()
372
+ attention_mask = model_inputs['attention_mask'].cuda()
373
+ generation_config['eos_token_id'] = eos_token_id
374
+ generation_output = self.generate(
375
+ pixel_values=pixel_values,
376
+ visual_features=visual_features,
377
+ input_ids=input_ids,
378
+ attention_mask=attention_mask,
379
+ **generation_config
380
+ )
381
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
382
+ response = response.split(template.sep)[0].strip()
383
+
384
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
385
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
386
+ if verbose:
387
+ print(query_to_print, response)
388
+ return response
389
+
390
+ @torch.no_grad()
391
+ def generate(
392
+ self,
393
+ pixel_values: Optional[torch.FloatTensor] = None,
394
+ input_ids: Optional[torch.FloatTensor] = None,
395
+ attention_mask: Optional[torch.LongTensor] = None,
396
+ visual_features: Optional[torch.FloatTensor] = None,
397
+ generation_config: Optional[GenerationConfig] = None,
398
+ output_hidden_states: Optional[bool] = None,
399
+ return_dict: Optional[bool] = None,
400
+ **generate_kwargs,
401
+ ) -> torch.LongTensor:
402
+
403
+ # assert self.img_context_token_id is not None
404
+ if pixel_values is not None:
405
+ if visual_features is not None:
406
+ vit_embeds = visual_features.cuda()
407
+ vit_embeds = self.mlp1(vit_embeds)
408
+ else:
409
+ vit_embeds = self.extract_feature(pixel_values)
410
+
411
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
412
+ B, N, C = input_embeds.shape
413
+ input_embeds = input_embeds.reshape(B * N, C)
414
+
415
+ input_ids = input_ids.reshape(B * N)
416
+ selected = (input_ids == self.img_context_token_id)
417
+ assert selected.sum() != 0
418
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
419
+
420
+ input_embeds = input_embeds.reshape(B, N, C)
421
+ else:
422
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
423
+
424
+ outputs = self.language_model.generate(
425
+ inputs_embeds=input_embeds,
426
+ attention_mask=attention_mask,
427
+ generation_config=generation_config,
428
+ output_hidden_states=output_hidden_states,
429
+ return_dict=return_dict,
430
+ use_cache=True,
431
+ **generate_kwargs,
432
+ )
433
+
434
+ return outputs
recipe.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ DEFAULT_stage:
2
+ DEFAULT_modifiers:
3
+ QuantizationModifier:
4
+ ignore: ['re:.*lm_head', 're:mlp1.*', 're:vision_model.*']
5
+ targets: Linear
6
+ scheme: FP8_DYNAMIC
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafa
3
+ size 11421896
tokenizer_config.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
199
+ "clean_up_tokenization_spaces": false,
200
+ "eos_token": "<|im_end|>",
201
+ "errors": "replace",
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "split_special_tokens": false,
205
+ "tokenizer_class": "Qwen2Tokenizer",
206
+ "unk_token": null
207
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff