katuni4ka commited on
Commit
7515daa
1 Parent(s): 1e2b664

Upload 15 files

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,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 151654,
3
+ "</img>": 151647,
4
+ "</quad>": 151650,
5
+ "</ref>": 151652,
6
+ "<IMG_CONTEXT>": 151648,
7
+ "<box>": 151653,
8
+ "<img>": 151646,
9
+ "<quad>": 151649,
10
+ "<ref>": 151651,
11
+ "<|endoftext|>": 151643,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644
14
+ }
config.json ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "_name_or_path": "/home/ea/work/my_optimum_intel/optimum-intel/internvl2-tiny",
4
+ "architectures": [
5
+ "InternVLChatModel"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_internvl_chat.InternVLChatConfig",
9
+ "AutoModel": "modeling_internvl_chat.InternVLChatModel",
10
+ "AutoModelForCausalLM": "modeling_internvl_chat.InternVLChatModel"
11
+ },
12
+ "downsample_ratio": 0.5,
13
+ "dynamic_image_size": true,
14
+ "force_image_size": 28,
15
+ "img_context_token_id": 151648,
16
+ "llm_config": {
17
+ "_name_or_path": "Qwen/Qwen2-0.5B-Instruct",
18
+ "add_cross_attention": false,
19
+ "architectures": [
20
+ "Qwen2ForCausalLM"
21
+ ],
22
+ "attention_dropout": 0.0,
23
+ "bad_words_ids": null,
24
+ "begin_suppress_tokens": null,
25
+ "bos_token_id": 151643,
26
+ "chunk_size_feed_forward": 0,
27
+ "cross_attention_hidden_size": null,
28
+ "decoder_start_token_id": null,
29
+ "diversity_penalty": 0.0,
30
+ "do_sample": false,
31
+ "early_stopping": false,
32
+ "encoder_no_repeat_ngram_size": 0,
33
+ "eos_token_id": 151645,
34
+ "exponential_decay_length_penalty": null,
35
+ "finetuning_task": null,
36
+ "forced_bos_token_id": null,
37
+ "forced_eos_token_id": null,
38
+ "hidden_act": "silu",
39
+ "hidden_size": 56,
40
+ "id2label": {
41
+ "0": "LABEL_0",
42
+ "1": "LABEL_1"
43
+ },
44
+ "initializer_range": 0.02,
45
+ "intermediate_size": 76,
46
+ "is_decoder": false,
47
+ "is_encoder_decoder": false,
48
+ "label2id": {
49
+ "LABEL_0": 0,
50
+ "LABEL_1": 1
51
+ },
52
+ "length_penalty": 1.0,
53
+ "max_length": 20,
54
+ "max_position_embeddings": 32768,
55
+ "max_window_layers": 2,
56
+ "min_length": 0,
57
+ "model_type": "qwen2",
58
+ "no_repeat_ngram_size": 0,
59
+ "num_attention_heads": 2,
60
+ "num_beam_groups": 1,
61
+ "num_beams": 1,
62
+ "num_hidden_layers": 2,
63
+ "num_key_value_heads": 2,
64
+ "num_return_sequences": 1,
65
+ "output_attentions": false,
66
+ "output_hidden_states": false,
67
+ "output_scores": false,
68
+ "pad_token_id": null,
69
+ "prefix": null,
70
+ "problem_type": null,
71
+ "pruned_heads": {},
72
+ "remove_invalid_values": false,
73
+ "repetition_penalty": 1.0,
74
+ "return_dict": true,
75
+ "return_dict_in_generate": false,
76
+ "rms_norm_eps": 1e-06,
77
+ "rope_scaling": null,
78
+ "rope_theta": 1000000.0,
79
+ "sep_token_id": null,
80
+ "sliding_window": null,
81
+ "suppress_tokens": null,
82
+ "task_specific_params": null,
83
+ "temperature": 1.0,
84
+ "tf_legacy_loss": false,
85
+ "tie_encoder_decoder": false,
86
+ "tie_word_embeddings": true,
87
+ "tokenizer_class": null,
88
+ "top_k": 50,
89
+ "top_p": 1.0,
90
+ "torch_dtype": "bfloat16",
91
+ "torchscript": false,
92
+ "transformers_version": "4.45.2",
93
+ "typical_p": 1.0,
94
+ "use_bfloat16": true,
95
+ "use_cache": true,
96
+ "use_sliding_window": false,
97
+ "vocab_size": 151655
98
+ },
99
+ "max_dynamic_patch": 12,
100
+ "min_dynamic_patch": 1,
101
+ "model_type": "internvl_chat",
102
+ "ps_version": "v2",
103
+ "select_layer": -1,
104
+ "template": "Hermes-2",
105
+ "torch_dtype": "float32",
106
+ "transformers_version": null,
107
+ "use_backbone_lora": 0,
108
+ "use_llm_lora": 0,
109
+ "use_thumbnail": true,
110
+ "vision_config": {
111
+ "_name_or_path": "",
112
+ "add_cross_attention": false,
113
+ "architectures": [
114
+ "InternVisionModel"
115
+ ],
116
+ "attention_dropout": 0.0,
117
+ "bad_words_ids": null,
118
+ "begin_suppress_tokens": null,
119
+ "bos_token_id": null,
120
+ "chunk_size_feed_forward": 0,
121
+ "cross_attention_hidden_size": null,
122
+ "decoder_start_token_id": null,
123
+ "diversity_penalty": 0.0,
124
+ "do_sample": false,
125
+ "drop_path_rate": 0.0,
126
+ "dropout": 0.0,
127
+ "early_stopping": false,
128
+ "encoder_no_repeat_ngram_size": 0,
129
+ "eos_token_id": null,
130
+ "exponential_decay_length_penalty": null,
131
+ "finetuning_task": null,
132
+ "forced_bos_token_id": null,
133
+ "forced_eos_token_id": null,
134
+ "hidden_act": "gelu",
135
+ "hidden_size": 32,
136
+ "id2label": {
137
+ "0": "LABEL_0",
138
+ "1": "LABEL_1"
139
+ },
140
+ "image_size": 28,
141
+ "initializer_factor": 1.0,
142
+ "initializer_range": 0.02,
143
+ "intermediate_size": 64,
144
+ "is_decoder": false,
145
+ "is_encoder_decoder": false,
146
+ "label2id": {
147
+ "LABEL_0": 0,
148
+ "LABEL_1": 1
149
+ },
150
+ "layer_norm_eps": 1e-06,
151
+ "length_penalty": 1.0,
152
+ "max_length": 20,
153
+ "min_length": 0,
154
+ "model_type": "intern_vit_6b",
155
+ "no_repeat_ngram_size": 0,
156
+ "norm_type": "layer_norm",
157
+ "num_attention_heads": 16,
158
+ "num_beam_groups": 1,
159
+ "num_beams": 1,
160
+ "num_channels": 3,
161
+ "num_hidden_layers": 2,
162
+ "num_return_sequences": 1,
163
+ "output_attentions": false,
164
+ "output_hidden_states": false,
165
+ "output_scores": false,
166
+ "pad_token_id": null,
167
+ "patch_size": 2,
168
+ "prefix": null,
169
+ "problem_type": null,
170
+ "pruned_heads": {},
171
+ "qk_normalization": false,
172
+ "qkv_bias": true,
173
+ "remove_invalid_values": false,
174
+ "repetition_penalty": 1.0,
175
+ "return_dict": true,
176
+ "return_dict_in_generate": false,
177
+ "sep_token_id": null,
178
+ "suppress_tokens": null,
179
+ "task_specific_params": null,
180
+ "temperature": 1.0,
181
+ "tf_legacy_loss": false,
182
+ "tie_encoder_decoder": false,
183
+ "tie_word_embeddings": true,
184
+ "tokenizer_class": null,
185
+ "top_k": 50,
186
+ "top_p": 1.0,
187
+ "torch_dtype": "bfloat16",
188
+ "torchscript": false,
189
+ "transformers_version": "4.45.2",
190
+ "typical_p": 1.0,
191
+ "use_bfloat16": true,
192
+ "use_flash_attn": false
193
+ }
194
+ }
configuration_intern_vit.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+
16
+ class InternVisionConfig(PretrainedConfig):
17
+ r"""
18
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
19
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
20
+
21
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
22
+ documentation from [`PretrainedConfig`] for more information.
23
+
24
+ Args:
25
+ num_channels (`int`, *optional*, defaults to 3):
26
+ Number of color channels in the input images (e.g., 3 for RGB).
27
+ patch_size (`int`, *optional*, defaults to 14):
28
+ The size (resolution) of each patch.
29
+ image_size (`int`, *optional*, defaults to 224):
30
+ The size (resolution) of each image.
31
+ qkv_bias (`bool`, *optional*, defaults to `False`):
32
+ Whether to add a bias to the queries and values in the self-attention layers.
33
+ hidden_size (`int`, *optional*, defaults to 3200):
34
+ Dimensionality of the encoder layers and the pooler layer.
35
+ num_attention_heads (`int`, *optional*, defaults to 25):
36
+ Number of attention heads for each attention layer in the Transformer encoder.
37
+ intermediate_size (`int`, *optional*, defaults to 12800):
38
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
39
+ qk_normalization (`bool`, *optional*, defaults to `True`):
40
+ Whether to normalize the queries and keys in the self-attention layers.
41
+ num_hidden_layers (`int`, *optional*, defaults to 48):
42
+ Number of hidden layers in the Transformer encoder.
43
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
44
+ Whether to use flash attention mechanism.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
46
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
47
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
48
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
49
+ The epsilon used by the layer normalization layers.
50
+ dropout (`float`, *optional*, defaults to 0.0):
51
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
52
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
53
+ Dropout rate for stochastic depth.
54
+ attention_dropout (`float`, *optional*, defaults to 0.0):
55
+ The dropout ratio for the attention probabilities.
56
+ initializer_range (`float`, *optional*, defaults to 0.02):
57
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
58
+ initializer_factor (`float`, *optional*, defaults to 0.1):
59
+ A factor for layer scale.
60
+ """
61
+
62
+ model_type = "intern_vit_6b"
63
+
64
+ def __init__(
65
+ self,
66
+ num_channels=3,
67
+ patch_size=14,
68
+ image_size=224,
69
+ qkv_bias=False,
70
+ hidden_size=3200,
71
+ num_attention_heads=25,
72
+ intermediate_size=12800,
73
+ qk_normalization=True,
74
+ num_hidden_layers=48,
75
+ use_flash_attn=True,
76
+ hidden_act="gelu",
77
+ norm_type="rms_norm",
78
+ layer_norm_eps=1e-6,
79
+ dropout=0.0,
80
+ drop_path_rate=0.0,
81
+ attention_dropout=0.0,
82
+ initializer_range=0.02,
83
+ initializer_factor=0.1,
84
+ **kwargs,
85
+ ):
86
+ super().__init__(**kwargs)
87
+
88
+ self.hidden_size = hidden_size
89
+ self.intermediate_size = intermediate_size
90
+ self.dropout = dropout
91
+ self.drop_path_rate = drop_path_rate
92
+ self.num_hidden_layers = num_hidden_layers
93
+ self.num_attention_heads = num_attention_heads
94
+ self.num_channels = num_channels
95
+ self.patch_size = patch_size
96
+ self.image_size = image_size
97
+ self.initializer_range = initializer_range
98
+ self.initializer_factor = initializer_factor
99
+ self.attention_dropout = attention_dropout
100
+ self.layer_norm_eps = layer_norm_eps
101
+ self.hidden_act = hidden_act
102
+ self.norm_type = norm_type
103
+ self.qkv_bias = qkv_bias
104
+ self.qk_normalization = qk_normalization
105
+ self.use_flash_attn = use_flash_attn
106
+
107
+ @classmethod
108
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
109
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
110
+
111
+ if "vision_config" in config_dict:
112
+ config_dict = config_dict["vision_config"]
113
+
114
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
115
+ logger.warning(
116
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
117
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
118
+ )
119
+
120
+ return cls.from_dict(config_dict, **kwargs)
configuration_internvl_chat.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import copy
8
+
9
+ from transformers import LlamaConfig, Qwen2Config
10
+ from transformers.configuration_utils import PretrainedConfig
11
+ from transformers.utils import logging
12
+
13
+ from .configuration_intern_vit import InternVisionConfig
14
+
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+
19
+ class InternVLChatConfig(PretrainedConfig):
20
+ model_type = "internvl_chat"
21
+ is_composition = True
22
+
23
+ def __init__(
24
+ self,
25
+ vision_config=None,
26
+ llm_config=None,
27
+ use_backbone_lora=0,
28
+ use_llm_lora=0,
29
+ select_layer=-1,
30
+ force_image_size=None,
31
+ downsample_ratio=0.5,
32
+ template=None,
33
+ dynamic_image_size=False,
34
+ use_thumbnail=False,
35
+ ps_version="v1",
36
+ min_dynamic_patch=1,
37
+ max_dynamic_patch=6,
38
+ **kwargs,
39
+ ):
40
+ super().__init__(**kwargs)
41
+
42
+ if vision_config is None:
43
+ vision_config = {}
44
+ logger.info("vision_config is None. Initializing the InternVisionConfig with default values.")
45
+
46
+ if llm_config is None:
47
+ llm_config = {"architectures": ["Qwen2ForCausalLM"]}
48
+ logger.info("llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).")
49
+
50
+ self.vision_config = InternVisionConfig(**vision_config)
51
+ if llm_config["architectures"][0] == "LlamaForCausalLM":
52
+ self.llm_config = LlamaConfig(**llm_config)
53
+ elif llm_config["architectures"][0] == "Qwen2ForCausalLM":
54
+ self.llm_config = Qwen2Config(**llm_config)
55
+ else:
56
+ raise ValueError("Unsupported architecture: {}".format(llm_config["architectures"][0]))
57
+ self.use_backbone_lora = use_backbone_lora
58
+ self.use_llm_lora = use_llm_lora
59
+ self.select_layer = select_layer
60
+ self.force_image_size = force_image_size
61
+ self.downsample_ratio = downsample_ratio
62
+ self.template = template
63
+ self.dynamic_image_size = dynamic_image_size
64
+ self.use_thumbnail = use_thumbnail
65
+ self.ps_version = ps_version # pixel shuffle version
66
+ self.min_dynamic_patch = min_dynamic_patch
67
+ self.max_dynamic_patch = max_dynamic_patch
68
+
69
+ logger.info(f"vision_select_layer: {self.select_layer}")
70
+ logger.info(f"ps_version: {self.ps_version}")
71
+ logger.info(f"min_dynamic_patch: {self.min_dynamic_patch}")
72
+ logger.info(f"max_dynamic_patch: {self.max_dynamic_patch}")
73
+
74
+ def to_dict(self):
75
+ """
76
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
77
+
78
+ Returns:
79
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
80
+ """
81
+ output = copy.deepcopy(self.__dict__)
82
+ output["vision_config"] = self.vision_config.to_dict()
83
+ output["llm_config"] = self.llm_config.to_dict()
84
+ output["model_type"] = self.__class__.model_type
85
+ output["use_backbone_lora"] = self.use_backbone_lora
86
+ output["use_llm_lora"] = self.use_llm_lora
87
+ output["select_layer"] = self.select_layer
88
+ output["force_image_size"] = self.force_image_size
89
+ output["downsample_ratio"] = self.downsample_ratio
90
+ output["template"] = self.template
91
+ output["dynamic_image_size"] = self.dynamic_image_size
92
+ output["use_thumbnail"] = self.use_thumbnail
93
+ output["ps_version"] = self.ps_version
94
+ output["min_dynamic_patch"] = self.min_dynamic_patch
95
+ output["max_dynamic_patch"] = self.max_dynamic_patch
96
+
97
+ return output
conversation.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+ """
7
+
8
+ import dataclasses
9
+ from enum import IntEnum, auto
10
+ from typing import Dict, List, Tuple, Union
11
+
12
+
13
+ class SeparatorStyle(IntEnum):
14
+ """Separator styles."""
15
+
16
+ ADD_COLON_SINGLE = auto()
17
+ ADD_COLON_TWO = auto()
18
+ ADD_COLON_SPACE_SINGLE = auto()
19
+ NO_COLON_SINGLE = auto()
20
+ NO_COLON_TWO = auto()
21
+ ADD_NEW_LINE_SINGLE = auto()
22
+ LLAMA2 = auto()
23
+ CHATGLM = auto()
24
+ CHATML = auto()
25
+ CHATINTERN = auto()
26
+ DOLLY = auto()
27
+ RWKV = auto()
28
+ PHOENIX = auto()
29
+ ROBIN = auto()
30
+ FALCON_CHAT = auto()
31
+ CHATGLM3 = auto()
32
+ INTERNVL_ZH = auto()
33
+ MPT = auto()
34
+
35
+
36
+ @dataclasses.dataclass
37
+ class Conversation:
38
+ """A class that manages prompt templates and keeps all conversation history."""
39
+
40
+ # The name of this template
41
+ name: str
42
+ # The template of the system prompt
43
+ system_template: str = "{system_message}"
44
+ # The system message
45
+ system_message: str = ""
46
+ # The names of two roles
47
+ roles: Tuple[str] = ("USER", "ASSISTANT")
48
+ # All messages. Each item is (role, message).
49
+ messages: List[List[str]] = ()
50
+ # The number of few shot examples
51
+ offset: int = 0
52
+ # The separator style and configurations
53
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
54
+ sep: str = "\n"
55
+ sep2: str = None
56
+ # Stop criteria (the default one is EOS token)
57
+ stop_str: Union[str, List[str]] = None
58
+ # Stops generation if meeting any token in this list
59
+ stop_token_ids: List[int] = None
60
+
61
+ def get_prompt(self) -> str:
62
+ """Get the prompt for generation."""
63
+ system_prompt = self.system_template.format(system_message=self.system_message)
64
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
65
+ ret = system_prompt + self.sep
66
+ for role, message in self.messages:
67
+ if message:
68
+ ret += role + ": " + message + self.sep
69
+ else:
70
+ ret += role + ":"
71
+ return ret
72
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
73
+ seps = [self.sep, self.sep2]
74
+ ret = system_prompt + seps[0]
75
+ for i, (role, message) in enumerate(self.messages):
76
+ if message:
77
+ ret += role + ": " + message + seps[i % 2]
78
+ else:
79
+ ret += role + ":"
80
+ return ret
81
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
82
+ ret = system_prompt + self.sep
83
+ for role, message in self.messages:
84
+ if message:
85
+ ret += role + ": " + message + self.sep
86
+ else:
87
+ ret += role + ": " # must be end with a space
88
+ return ret
89
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
90
+ ret = "" if system_prompt == "" else system_prompt + self.sep
91
+ for role, message in self.messages:
92
+ if message:
93
+ ret += role + "\n" + message + self.sep
94
+ else:
95
+ ret += role + "\n"
96
+ return ret
97
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
98
+ ret = system_prompt
99
+ for role, message in self.messages:
100
+ if message:
101
+ ret += role + message + self.sep
102
+ else:
103
+ ret += role
104
+ return ret
105
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
106
+ seps = [self.sep, self.sep2]
107
+ ret = system_prompt
108
+ for i, (role, message) in enumerate(self.messages):
109
+ if message:
110
+ ret += role + message + seps[i % 2]
111
+ else:
112
+ ret += role
113
+ return ret
114
+ elif self.sep_style == SeparatorStyle.RWKV:
115
+ ret = system_prompt
116
+ for i, (role, message) in enumerate(self.messages):
117
+ if message:
118
+ ret += role + ": " + message.replace("\r\n", "\n").replace("\n\n", "\n")
119
+ ret += "\n\n"
120
+ else:
121
+ ret += role + ":"
122
+ return ret
123
+ elif self.sep_style == SeparatorStyle.LLAMA2:
124
+ seps = [self.sep, self.sep2]
125
+ if self.system_message:
126
+ ret = system_prompt
127
+ else:
128
+ ret = "[INST] "
129
+ for i, (role, message) in enumerate(self.messages):
130
+ tag = self.roles[i % 2]
131
+ if message:
132
+ if i == 0:
133
+ ret += message + " "
134
+ else:
135
+ ret += tag + " " + message + seps[i % 2]
136
+ else:
137
+ ret += tag
138
+ return ret
139
+ elif self.sep_style == SeparatorStyle.CHATGLM:
140
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
141
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
142
+ round_add_n = 1 if self.name == "chatglm2" else 0
143
+ if system_prompt:
144
+ ret = system_prompt + self.sep
145
+ else:
146
+ ret = ""
147
+
148
+ for i, (role, message) in enumerate(self.messages):
149
+ if i % 2 == 0:
150
+ ret += f"[Round {i//2 + round_add_n}]{self.sep}"
151
+
152
+ if message:
153
+ ret += f"{role}:{message}{self.sep}"
154
+ else:
155
+ ret += f"{role}:"
156
+ return ret
157
+ elif self.sep_style == SeparatorStyle.CHATML:
158
+ ret = "" if system_prompt == "" else system_prompt + self.sep + "\n"
159
+ for role, message in self.messages:
160
+ if message:
161
+ ret += role + "\n" + message + self.sep + "\n"
162
+ else:
163
+ ret += role + "\n"
164
+ return ret
165
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
166
+ ret = ""
167
+ if self.system_message:
168
+ ret += system_prompt
169
+ for role, message in self.messages:
170
+ if message:
171
+ ret += role + "\n" + " " + message
172
+ else:
173
+ ret += role
174
+ return ret
175
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
176
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
177
+ seps = [self.sep, self.sep2]
178
+ ret = system_prompt
179
+ for i, (role, message) in enumerate(self.messages):
180
+ # if i % 2 == 0:
181
+ # ret += "<s>"
182
+ if message:
183
+ ret += role + ":" + message + seps[i % 2] + "\n"
184
+ else:
185
+ ret += role + ":"
186
+ return ret
187
+ elif self.sep_style == SeparatorStyle.DOLLY:
188
+ seps = [self.sep, self.sep2]
189
+ ret = system_prompt
190
+ for i, (role, message) in enumerate(self.messages):
191
+ if message:
192
+ ret += role + ":\n" + message + seps[i % 2]
193
+ if i % 2 == 1:
194
+ ret += "\n\n"
195
+ else:
196
+ ret += role + ":\n"
197
+ return ret
198
+ elif self.sep_style == SeparatorStyle.PHOENIX:
199
+ ret = system_prompt
200
+ for role, message in self.messages:
201
+ if message:
202
+ ret += role + ": " + "<s>" + message + "</s>"
203
+ else:
204
+ ret += role + ": " + "<s>"
205
+ return ret
206
+ elif self.sep_style == SeparatorStyle.ROBIN:
207
+ ret = system_prompt + self.sep
208
+ for role, message in self.messages:
209
+ if message:
210
+ ret += role + ":\n" + message + self.sep
211
+ else:
212
+ ret += role + ":\n"
213
+ return ret
214
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
215
+ ret = ""
216
+ if self.system_message:
217
+ ret += system_prompt + self.sep
218
+ for role, message in self.messages:
219
+ if message:
220
+ ret += role + ": " + message + self.sep
221
+ else:
222
+ ret += role + ":"
223
+
224
+ return ret
225
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
226
+ seps = [self.sep, self.sep2]
227
+ ret = self.system_message + seps[0]
228
+ for i, (role, message) in enumerate(self.messages):
229
+ if message:
230
+ ret += role + ": " + message + seps[i % 2]
231
+ else:
232
+ ret += role + ":"
233
+ return ret
234
+ elif self.sep_style == SeparatorStyle.MPT:
235
+ ret = system_prompt + self.sep
236
+ for role, message in self.messages:
237
+ if message:
238
+ if type(message) is tuple:
239
+ message, _, _ = message
240
+ ret += role + message + self.sep
241
+ else:
242
+ ret += role
243
+ return ret
244
+ else:
245
+ raise ValueError(f"Invalid style: {self.sep_style}")
246
+
247
+ def set_system_message(self, system_message: str):
248
+ """Set the system message."""
249
+ self.system_message = system_message
250
+
251
+ def append_message(self, role: str, message: str):
252
+ """Append a new message."""
253
+ self.messages.append([role, message])
254
+
255
+ def update_last_message(self, message: str):
256
+ """Update the last output.
257
+
258
+ The last message is typically set to be None when constructing the prompt,
259
+ so we need to update it in-place after getting the response from a model.
260
+ """
261
+ self.messages[-1][1] = message
262
+
263
+ def to_gradio_chatbot(self):
264
+ """Convert the conversation to gradio chatbot format."""
265
+ ret = []
266
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
267
+ if i % 2 == 0:
268
+ ret.append([msg, None])
269
+ else:
270
+ ret[-1][-1] = msg
271
+ return ret
272
+
273
+ def to_openai_api_messages(self):
274
+ """Convert the conversation to OpenAI chat completion format."""
275
+ ret = [{"role": "system", "content": self.system_message}]
276
+
277
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
278
+ if i % 2 == 0:
279
+ ret.append({"role": "user", "content": msg})
280
+ else:
281
+ if msg is not None:
282
+ ret.append({"role": "assistant", "content": msg})
283
+ return ret
284
+
285
+ def copy(self):
286
+ return Conversation(
287
+ name=self.name,
288
+ system_template=self.system_template,
289
+ system_message=self.system_message,
290
+ roles=self.roles,
291
+ messages=[[x, y] for x, y in self.messages],
292
+ offset=self.offset,
293
+ sep_style=self.sep_style,
294
+ sep=self.sep,
295
+ sep2=self.sep2,
296
+ stop_str=self.stop_str,
297
+ stop_token_ids=self.stop_token_ids,
298
+ )
299
+
300
+ def dict(self):
301
+ return {
302
+ "template_name": self.name,
303
+ "system_message": self.system_message,
304
+ "roles": self.roles,
305
+ "messages": self.messages,
306
+ "offset": self.offset,
307
+ }
308
+
309
+
310
+ # A global registry for all conversation templates
311
+ conv_templates: Dict[str, Conversation] = {}
312
+
313
+
314
+ def register_conv_template(template: Conversation, override: bool = False):
315
+ """Register a new conversation template."""
316
+ if not override:
317
+ assert template.name not in conv_templates, f"{template.name} has been registered."
318
+
319
+ conv_templates[template.name] = template
320
+
321
+
322
+ def get_conv_template(name: str) -> Conversation:
323
+ """Get a conversation template."""
324
+ return conv_templates[name].copy()
325
+
326
+
327
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
328
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
329
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
330
+ # Therefore, they are completely equivalent during inference.
331
+ register_conv_template(
332
+ Conversation(
333
+ name="Hermes-2",
334
+ system_template="<|im_start|>system\n{system_message}",
335
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
336
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
337
+ system_message="你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。",
338
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
339
+ sep_style=SeparatorStyle.MPT,
340
+ sep="<|im_end|>",
341
+ stop_token_ids=[
342
+ 2,
343
+ 6,
344
+ 7,
345
+ 8,
346
+ ],
347
+ stop_str="<|endoftext|>",
348
+ )
349
+ )
350
+
351
+
352
+ register_conv_template(
353
+ Conversation(
354
+ name="internlm2-chat",
355
+ system_template="<|im_start|>system\n{system_message}",
356
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
357
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
358
+ system_message="你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。",
359
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
360
+ sep_style=SeparatorStyle.MPT,
361
+ sep="<|im_end|>",
362
+ stop_token_ids=[2, 92543, 92542],
363
+ )
364
+ )
365
+
366
+
367
+ register_conv_template(
368
+ Conversation(
369
+ name="phi3-chat",
370
+ system_template="<|system|>\n{system_message}",
371
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
372
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
373
+ system_message="你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。",
374
+ roles=("<|user|>\n", "<|assistant|>\n"),
375
+ sep_style=SeparatorStyle.MPT,
376
+ sep="<|end|>",
377
+ stop_token_ids=[2, 32000, 32007],
378
+ )
379
+ )
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.45.2"
4
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c91dc9c94bbae4e6d8d16aab28765983e8b12cd0565b9e8a98f80073b0b5e14
3
+ size 34321392
modeling_intern_vit.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ from typing import Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from einops import rearrange
12
+ from timm.models.layers import DropPath
13
+ from torch import nn
14
+ from transformers.activations import ACT2FN
15
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
16
+ from transformers.modeling_utils import PreTrainedModel
17
+ from transformers.utils import logging
18
+
19
+ from .configuration_intern_vit import InternVisionConfig
20
+
21
+
22
+ try:
23
+ from flash_attn.bert_padding import pad_input, unpad_input
24
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func
25
+
26
+ has_flash_attn = True
27
+ except:
28
+ print("FlashAttention2 is not installed.")
29
+ has_flash_attn = False
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ class FlashAttention(nn.Module):
35
+ """Implement the scaled dot product attention with softmax.
36
+ Arguments
37
+ ---------
38
+ softmax_scale: The temperature to use for the softmax attention.
39
+ (default: 1/sqrt(d_keys) where d_keys is computed at
40
+ runtime)
41
+ attention_dropout: The dropout rate to apply to the attention
42
+ (default: 0.0)
43
+ """
44
+
45
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
46
+ super().__init__()
47
+ self.softmax_scale = softmax_scale
48
+ self.dropout_p = attention_dropout
49
+
50
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None, max_s=None, need_weights=False):
51
+ """Implements the multihead softmax attention.
52
+ Arguments
53
+ ---------
54
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
55
+ if unpadded: (nnz, 3, h, d)
56
+ key_padding_mask: a bool tensor of shape (B, S)
57
+ """
58
+ assert not need_weights
59
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
60
+ assert qkv.is_cuda
61
+
62
+ if cu_seqlens is None:
63
+ batch_size = qkv.shape[0]
64
+ seqlen = qkv.shape[1]
65
+ if key_padding_mask is None:
66
+ qkv = rearrange(qkv, "b s ... -> (b s) ...")
67
+ max_s = seqlen
68
+ cu_seqlens = torch.arange(
69
+ 0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32, device=qkv.device
70
+ )
71
+ output = flash_attn_varlen_qkvpacked_func(
72
+ qkv,
73
+ cu_seqlens,
74
+ max_s,
75
+ self.dropout_p if self.training else 0.0,
76
+ softmax_scale=self.softmax_scale,
77
+ causal=causal,
78
+ )
79
+ output = rearrange(output, "(b s) ... -> b s ...", b=batch_size)
80
+ else:
81
+ nheads = qkv.shape[-2]
82
+ x = rearrange(qkv, "b s three h d -> b s (three h d)")
83
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
84
+ x_unpad = rearrange(x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads)
85
+ output_unpad = flash_attn_varlen_qkvpacked_func(
86
+ x_unpad,
87
+ cu_seqlens,
88
+ max_s,
89
+ self.dropout_p if self.training else 0.0,
90
+ softmax_scale=self.softmax_scale,
91
+ causal=causal,
92
+ )
93
+ output = rearrange(
94
+ pad_input(rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, batch_size, seqlen),
95
+ "b s (h d) -> b s h d",
96
+ h=nheads,
97
+ )
98
+ else:
99
+ assert max_s is not None
100
+ output = flash_attn_varlen_qkvpacked_func(
101
+ qkv,
102
+ cu_seqlens,
103
+ max_s,
104
+ self.dropout_p if self.training else 0.0,
105
+ softmax_scale=self.softmax_scale,
106
+ causal=causal,
107
+ )
108
+
109
+ return output, None
110
+
111
+
112
+ class InternRMSNorm(nn.Module):
113
+ def __init__(self, hidden_size, eps=1e-6):
114
+ super().__init__()
115
+ self.weight = nn.Parameter(torch.ones(hidden_size))
116
+ self.variance_epsilon = eps
117
+
118
+ def forward(self, hidden_states):
119
+ input_dtype = hidden_states.dtype
120
+ hidden_states = hidden_states.to(torch.float32)
121
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
122
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
123
+ return self.weight * hidden_states.to(input_dtype)
124
+
125
+
126
+ try:
127
+ from apex.normalization import FusedRMSNorm
128
+
129
+ InternRMSNorm = FusedRMSNorm # noqa
130
+
131
+ logger.info("Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm")
132
+ except ImportError:
133
+ # using the normal InternRMSNorm
134
+ pass
135
+ except Exception:
136
+ logger.warning("discovered apex but it failed to load, falling back to InternRMSNorm")
137
+ pass
138
+
139
+
140
+ NORM2FN = {
141
+ "rms_norm": InternRMSNorm,
142
+ "layer_norm": nn.LayerNorm,
143
+ }
144
+
145
+
146
+ class InternVisionEmbeddings(nn.Module):
147
+ def __init__(self, config: InternVisionConfig):
148
+ super().__init__()
149
+ self.config = config
150
+ self.embed_dim = config.hidden_size
151
+ self.image_size = config.image_size
152
+ self.patch_size = config.patch_size
153
+
154
+ self.class_embedding = nn.Parameter(
155
+ torch.randn(1, 1, self.embed_dim),
156
+ )
157
+
158
+ self.patch_embedding = nn.Conv2d(
159
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
160
+ )
161
+
162
+ self.num_patches = (self.image_size // self.patch_size) ** 2
163
+ self.num_positions = self.num_patches + 1
164
+
165
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
166
+
167
+ def _get_pos_embed(self, pos_embed, H, W):
168
+ target_dtype = pos_embed.dtype
169
+ pos_embed = (
170
+ pos_embed.float()
171
+ .reshape(1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1)
172
+ .permute(0, 3, 1, 2)
173
+ )
174
+ pos_embed = (
175
+ F.interpolate(pos_embed, size=(H, W), mode="bicubic", align_corners=False)
176
+ .reshape(1, -1, H * W)
177
+ .permute(0, 2, 1)
178
+ .to(target_dtype)
179
+ )
180
+ return pos_embed
181
+
182
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
183
+ target_dtype = self.patch_embedding.weight.dtype
184
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
185
+ batch_size, _, height, width = patch_embeds.shape
186
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
187
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
188
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
189
+ position_embedding = torch.cat(
190
+ [self.position_embedding[:, :1, :], self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)],
191
+ dim=1,
192
+ )
193
+ embeddings = embeddings + position_embedding.to(target_dtype)
194
+ return embeddings
195
+
196
+
197
+ class InternAttention(nn.Module):
198
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
199
+
200
+ def __init__(self, config: InternVisionConfig):
201
+ super().__init__()
202
+ self.config = config
203
+ self.embed_dim = config.hidden_size
204
+ self.num_heads = config.num_attention_heads
205
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
206
+ if config.use_flash_attn and not has_flash_attn:
207
+ print("Warning: Flash Attention is not available, use_flash_attn is set to False.")
208
+ self.head_dim = self.embed_dim // self.num_heads
209
+ if self.head_dim * self.num_heads != self.embed_dim:
210
+ raise ValueError(
211
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
212
+ f" {self.num_heads})."
213
+ )
214
+
215
+ self.scale = self.head_dim**-0.5
216
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
217
+ self.attn_drop = nn.Dropout(config.attention_dropout)
218
+ self.proj_drop = nn.Dropout(config.dropout)
219
+
220
+ self.qk_normalization = config.qk_normalization
221
+
222
+ if self.qk_normalization:
223
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
224
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
225
+
226
+ if self.use_flash_attn:
227
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
228
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
229
+
230
+ def _naive_attn(self, x):
231
+ B, N, C = x.shape
232
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
233
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
234
+
235
+ if self.qk_normalization:
236
+ B_, H_, N_, D_ = q.shape
237
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
238
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
239
+
240
+ attn = (q * self.scale) @ k.transpose(-2, -1)
241
+ attn = attn.softmax(dim=-1)
242
+ attn = self.attn_drop(attn)
243
+
244
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
245
+ x = self.proj(x)
246
+ x = self.proj_drop(x)
247
+ return x
248
+
249
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
250
+ qkv = self.qkv(x)
251
+ qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, h=self.num_heads)
252
+
253
+ if self.qk_normalization:
254
+ q, k, v = qkv.unbind(2)
255
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
256
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
257
+ qkv = torch.stack([q, k, v], dim=2)
258
+
259
+ context, _ = self.inner_attn(qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False)
260
+ outs = self.proj(rearrange(context, "b s h d -> b s (h d)"))
261
+ outs = self.proj_drop(outs)
262
+ return outs
263
+
264
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
265
+ x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
266
+ return x
267
+
268
+
269
+ class InternMLP(nn.Module):
270
+ def __init__(self, config: InternVisionConfig):
271
+ super().__init__()
272
+ self.config = config
273
+ self.act = ACT2FN[config.hidden_act]
274
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
275
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
276
+
277
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
278
+ hidden_states = self.fc1(hidden_states)
279
+ hidden_states = self.act(hidden_states)
280
+ hidden_states = self.fc2(hidden_states)
281
+ return hidden_states
282
+
283
+
284
+ class InternVisionEncoderLayer(nn.Module):
285
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
286
+ super().__init__()
287
+ self.embed_dim = config.hidden_size
288
+ self.intermediate_size = config.intermediate_size
289
+ self.norm_type = config.norm_type
290
+
291
+ self.attn = InternAttention(config)
292
+ self.mlp = InternMLP(config)
293
+ self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
294
+ self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
295
+
296
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
297
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
298
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
299
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
300
+
301
+ def forward(
302
+ self,
303
+ hidden_states: torch.Tensor,
304
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
305
+ """
306
+ Args:
307
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
308
+ """
309
+ hidden_states = hidden_states + self.drop_path1(
310
+ self.attn(self.norm1(hidden_states).to(hidden_states.dtype)) * self.ls1
311
+ )
312
+
313
+ hidden_states = hidden_states + self.drop_path2(
314
+ self.mlp(self.norm2(hidden_states).to(hidden_states.dtype)) * self.ls2
315
+ )
316
+
317
+ return hidden_states
318
+
319
+
320
+ class InternVisionEncoder(nn.Module):
321
+ """
322
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
323
+ [`InternEncoderLayer`].
324
+
325
+ Args:
326
+ config (`InternConfig`):
327
+ The corresponding vision configuration for the `InternEncoder`.
328
+ """
329
+
330
+ def __init__(self, config: InternVisionConfig):
331
+ super().__init__()
332
+ self.config = config
333
+ # stochastic depth decay rule
334
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
335
+ self.layers = nn.ModuleList(
336
+ [InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)]
337
+ )
338
+ self.gradient_checkpointing = True
339
+
340
+ def forward(
341
+ self,
342
+ inputs_embeds,
343
+ output_hidden_states: Optional[bool] = None,
344
+ return_dict: Optional[bool] = None,
345
+ ) -> Union[Tuple, BaseModelOutput]:
346
+ r"""
347
+ Args:
348
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
349
+ Embedded representation of the inputs. Should be float, not int tokens.
350
+ output_hidden_states (`bool`, *optional*):
351
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
352
+ for more detail.
353
+ return_dict (`bool`, *optional*):
354
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
355
+ """
356
+ output_hidden_states = (
357
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
358
+ )
359
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
360
+
361
+ encoder_states = () if output_hidden_states else None
362
+ hidden_states = inputs_embeds
363
+
364
+ for idx, encoder_layer in enumerate(self.layers):
365
+ if output_hidden_states:
366
+ encoder_states = encoder_states + (hidden_states,)
367
+ if self.gradient_checkpointing and self.training:
368
+ layer_outputs = torch.utils.checkpoint.checkpoint(encoder_layer, hidden_states)
369
+ else:
370
+ layer_outputs = encoder_layer(
371
+ hidden_states,
372
+ )
373
+ hidden_states = layer_outputs
374
+
375
+ if output_hidden_states:
376
+ encoder_states = encoder_states + (hidden_states,)
377
+
378
+ if not return_dict:
379
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
380
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states)
381
+
382
+
383
+ class InternVisionModel(PreTrainedModel):
384
+ main_input_name = "pixel_values"
385
+ _supports_flash_attn_2 = True
386
+ config_class = InternVisionConfig
387
+ _no_split_modules = ["InternVisionEncoderLayer"]
388
+
389
+ def __init__(self, config: InternVisionConfig):
390
+ super().__init__(config)
391
+ self.config = config
392
+
393
+ self.embeddings = InternVisionEmbeddings(config)
394
+ self.encoder = InternVisionEncoder(config)
395
+
396
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
397
+ pos_emb = self.embeddings.position_embedding
398
+ _, num_positions, embed_dim = pos_emb.shape
399
+ cls_emb = pos_emb[:, :1, :]
400
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
401
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode="bicubic", align_corners=False)
402
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
403
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
404
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
405
+ self.embeddings.image_size = new_size
406
+ logger.info("Resized position embeddings from {} to {}".format(old_size, new_size))
407
+
408
+ def get_input_embeddings(self):
409
+ return self.embeddings
410
+
411
+ def forward(
412
+ self,
413
+ pixel_values: Optional[torch.FloatTensor] = None,
414
+ output_hidden_states: Optional[bool] = None,
415
+ return_dict: Optional[bool] = None,
416
+ pixel_embeds: Optional[torch.FloatTensor] = None,
417
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
418
+ output_hidden_states = (
419
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
420
+ )
421
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
422
+
423
+ if pixel_values is None and pixel_embeds is None:
424
+ raise ValueError("You have to specify pixel_values or pixel_embeds")
425
+
426
+ if pixel_embeds is not None:
427
+ hidden_states = pixel_embeds
428
+ else:
429
+ if len(pixel_values.shape) == 4:
430
+ hidden_states = self.embeddings(pixel_values)
431
+ else:
432
+ raise ValueError(f"wrong pixel_values size: {pixel_values.shape}")
433
+ encoder_outputs = self.encoder(
434
+ inputs_embeds=hidden_states,
435
+ output_hidden_states=output_hidden_states,
436
+ return_dict=return_dict,
437
+ )
438
+ last_hidden_state = encoder_outputs.last_hidden_state
439
+ pooled_output = last_hidden_state[:, 0, :]
440
+
441
+ if not return_dict:
442
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
443
+
444
+ return BaseModelOutputWithPooling(
445
+ last_hidden_state=last_hidden_state,
446
+ pooler_output=pooled_output,
447
+ hidden_states=encoder_outputs.hidden_states,
448
+ attentions=encoder_outputs.attentions,
449
+ )
modeling_internvl_chat.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import warnings
7
+ from typing import List, Optional, Tuple, Union
8
+
9
+ import torch.utils.checkpoint
10
+ import transformers
11
+ from torch import nn
12
+ from torch.nn import CrossEntropyLoss
13
+ from transformers import GenerationConfig, LlamaForCausalLM, Qwen2ForCausalLM
14
+ from transformers.modeling_outputs import CausalLMOutputWithPast
15
+ from transformers.modeling_utils import PreTrainedModel
16
+ from transformers.utils import logging
17
+
18
+ from .configuration_internvl_chat import InternVLChatConfig
19
+ from .conversation import get_conv_template
20
+ from .modeling_intern_vit import InternVisionModel, has_flash_attn
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ def version_cmp(v1, v2, op="eq"):
27
+ import operator
28
+
29
+ from packaging import version
30
+
31
+ op_func = getattr(operator, op)
32
+ return op_func(version.parse(v1), version.parse(v2))
33
+
34
+
35
+ class InternVLChatModel(PreTrainedModel):
36
+ config_class = InternVLChatConfig
37
+ main_input_name = "pixel_values"
38
+ base_model_prefix = "language_model"
39
+ _supports_flash_attn_2 = True
40
+ _no_split_modules = ["InternVisionModel", "LlamaDecoderLayer", "Qwen2DecoderLayer"]
41
+
42
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
43
+ super().__init__(config)
44
+
45
+ assert version_cmp(transformers.__version__, "4.37.0", "ge")
46
+ image_size = config.force_image_size or config.vision_config.image_size
47
+ patch_size = config.vision_config.patch_size
48
+ self.patch_size = patch_size
49
+ self.select_layer = config.select_layer
50
+ self.template = config.template
51
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio**2))
52
+ self.downsample_ratio = config.downsample_ratio
53
+ self.ps_version = config.ps_version
54
+ use_flash_attn = use_flash_attn if has_flash_attn else False
55
+ config.vision_config.use_flash_attn = True if use_flash_attn else False
56
+ config.llm_config._attn_implementation = "flash_attention_2" if use_flash_attn else "eager"
57
+
58
+ logger.info(f"num_image_token: {self.num_image_token}")
59
+ logger.info(f"ps_version: {self.ps_version}")
60
+ if vision_model is not None:
61
+ self.vision_model = vision_model
62
+ else:
63
+ self.vision_model = InternVisionModel(config.vision_config)
64
+ if language_model is not None:
65
+ self.language_model = language_model
66
+ else:
67
+ if config.llm_config.architectures[0] == "LlamaForCausalLM":
68
+ self.language_model = LlamaForCausalLM(config.llm_config)
69
+ elif config.llm_config.architectures[0] == "Qwen2ForCausalLM":
70
+ self.language_model = Qwen2ForCausalLM(config.llm_config)
71
+ else:
72
+ raise NotImplementedError(f"{config.llm_config.architectures[0]} is not implemented.")
73
+
74
+ vit_hidden_size = config.vision_config.hidden_size
75
+ llm_hidden_size = config.llm_config.hidden_size
76
+
77
+ self.mlp1 = nn.Sequential(
78
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
79
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
80
+ nn.GELU(),
81
+ nn.Linear(llm_hidden_size, llm_hidden_size),
82
+ )
83
+
84
+ self.img_context_token_id = None
85
+ self.conv_template = get_conv_template(self.template)
86
+ self.system_message = self.conv_template.system_message
87
+
88
+ def forward(
89
+ self,
90
+ pixel_values: torch.FloatTensor,
91
+ input_ids: torch.LongTensor = None,
92
+ attention_mask: Optional[torch.Tensor] = None,
93
+ position_ids: Optional[torch.LongTensor] = None,
94
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
95
+ labels: Optional[torch.LongTensor] = None,
96
+ use_cache: Optional[bool] = None,
97
+ output_attentions: Optional[bool] = None,
98
+ output_hidden_states: Optional[bool] = None,
99
+ return_dict: Optional[bool] = None,
100
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
101
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
102
+
103
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
104
+
105
+ vit_embeds = self.extract_feature(pixel_values)
106
+ vit_batch_size = pixel_values.shape[0]
107
+
108
+ B, N, C = input_embeds.shape
109
+ input_embeds = input_embeds.reshape(B * N, C)
110
+
111
+ input_ids = input_ids.reshape(B * N)
112
+ selected = input_ids == self.img_context_token_id
113
+ try:
114
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
115
+ except Exception as e:
116
+ vit_embeds = vit_embeds.reshape(-1, C)
117
+ print(
118
+ f"warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, "
119
+ f"vit_embeds.shape={vit_embeds.shape}"
120
+ )
121
+ n_token = selected.sum()
122
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
123
+
124
+ input_embeds = input_embeds.reshape(B, N, C)
125
+
126
+ outputs = self.language_model(
127
+ inputs_embeds=input_embeds,
128
+ attention_mask=attention_mask,
129
+ position_ids=position_ids,
130
+ past_key_values=past_key_values,
131
+ use_cache=use_cache,
132
+ output_attentions=output_attentions,
133
+ output_hidden_states=output_hidden_states,
134
+ return_dict=return_dict,
135
+ )
136
+ logits = outputs.logits
137
+
138
+ loss = None
139
+ if labels is not None:
140
+ # Shift so that tokens < n predict n
141
+ shift_logits = logits[..., :-1, :].contiguous()
142
+ shift_labels = labels[..., 1:].contiguous()
143
+ # Flatten the tokens
144
+ loss_fct = CrossEntropyLoss()
145
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
146
+ shift_labels = shift_labels.view(-1)
147
+ # Enable model parallelism
148
+ shift_labels = shift_labels.to(shift_logits.device)
149
+ loss = loss_fct(shift_logits, shift_labels)
150
+
151
+ if not return_dict:
152
+ output = (logits,) + outputs[1:]
153
+ return (loss,) + output if loss is not None else output
154
+
155
+ return CausalLMOutputWithPast(
156
+ loss=loss,
157
+ logits=logits,
158
+ past_key_values=outputs.past_key_values,
159
+ hidden_states=outputs.hidden_states,
160
+ attentions=outputs.attentions,
161
+ )
162
+
163
+ def pixel_shuffle(self, x, scale_factor=0.5):
164
+ n, w, h, c = x.size()
165
+ # N, W, H, C --> N, W, H * scale, C // scale
166
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
167
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
168
+ x = x.permute(0, 2, 1, 3).contiguous()
169
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
170
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor), int(c / (scale_factor * scale_factor)))
171
+ if self.ps_version == "v1":
172
+ warnings.warn(
173
+ "In ps_version 'v1', the height and width have not been swapped back, "
174
+ "which results in a transposed image."
175
+ )
176
+ else:
177
+ x = x.permute(0, 2, 1, 3).contiguous()
178
+ return x
179
+
180
+ def extract_feature(self, pixel_values):
181
+ if self.select_layer == -1:
182
+ vit_embeds = self.vision_model(
183
+ pixel_values=pixel_values, output_hidden_states=False, return_dict=True
184
+ ).last_hidden_state
185
+ else:
186
+ vit_embeds = self.vision_model(
187
+ pixel_values=pixel_values, output_hidden_states=True, return_dict=True
188
+ ).hidden_states[self.select_layer]
189
+ vit_embeds = vit_embeds[:, 1:, :]
190
+
191
+ h = w = int(vit_embeds.shape[1] ** 0.5)
192
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
193
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
194
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
195
+ vit_embeds = self.mlp1(vit_embeds)
196
+ return vit_embeds
197
+
198
+ def batch_chat(
199
+ self,
200
+ tokenizer,
201
+ pixel_values,
202
+ questions,
203
+ generation_config,
204
+ num_patches_list=None,
205
+ history=None,
206
+ return_history=False,
207
+ IMG_START_TOKEN="<img>",
208
+ IMG_END_TOKEN="</img>",
209
+ IMG_CONTEXT_TOKEN="<IMG_CONTEXT>",
210
+ verbose=False,
211
+ image_counts=None,
212
+ ):
213
+ if history is not None or return_history:
214
+ print("Now multi-turn chat is not supported in batch_chat.")
215
+ raise NotImplementedError
216
+
217
+ if image_counts is not None:
218
+ num_patches_list = image_counts
219
+ print("Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.")
220
+
221
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
222
+ self.img_context_token_id = img_context_token_id
223
+
224
+ if verbose and pixel_values is not None:
225
+ image_bs = pixel_values.shape[0]
226
+ print(f"dynamic ViT batch size: {image_bs}")
227
+
228
+ queries = []
229
+ for idx, num_patches in enumerate(num_patches_list):
230
+ question = questions[idx]
231
+ if pixel_values is not None and "<image>" not in question:
232
+ question = "<image>\n" + question
233
+ template = get_conv_template(self.template)
234
+ template.system_message = self.system_message
235
+ template.append_message(template.roles[0], question)
236
+ template.append_message(template.roles[1], None)
237
+ query = template.get_prompt()
238
+
239
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
240
+ query = query.replace("<image>", image_tokens, 1)
241
+ queries.append(query)
242
+
243
+ tokenizer.padding_side = "left"
244
+ model_inputs = tokenizer(queries, return_tensors="pt", padding=True)
245
+ input_ids = model_inputs["input_ids"].to(self.device)
246
+ attention_mask = model_inputs["attention_mask"].to(self.device)
247
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
248
+ generation_config["eos_token_id"] = eos_token_id
249
+ generation_output = self.generate(
250
+ pixel_values=pixel_values, input_ids=input_ids, attention_mask=attention_mask, **generation_config
251
+ )
252
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
253
+ responses = [response.split(template.sep)[0].strip() for response in responses]
254
+ return responses
255
+
256
+ def chat(
257
+ self,
258
+ tokenizer,
259
+ pixel_values,
260
+ question,
261
+ generation_config,
262
+ history=None,
263
+ return_history=False,
264
+ num_patches_list=None,
265
+ IMG_START_TOKEN="<img>",
266
+ IMG_END_TOKEN="</img>",
267
+ IMG_CONTEXT_TOKEN="<IMG_CONTEXT>",
268
+ verbose=False,
269
+ ):
270
+ if history is None and pixel_values is not None and "<image>" not in question:
271
+ question = "<image>\n" + question
272
+
273
+ if num_patches_list is None:
274
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
275
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
276
+
277
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
278
+ self.img_context_token_id = img_context_token_id
279
+
280
+ template = get_conv_template(self.template)
281
+ template.system_message = self.system_message
282
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
283
+
284
+ history = [] if history is None else history
285
+ for old_question, old_answer in history:
286
+ template.append_message(template.roles[0], old_question)
287
+ template.append_message(template.roles[1], old_answer)
288
+ template.append_message(template.roles[0], question)
289
+ template.append_message(template.roles[1], None)
290
+ query = template.get_prompt()
291
+
292
+ print(self.num_image_token)
293
+ print(num_patches_list)
294
+
295
+ if verbose and pixel_values is not None:
296
+ image_bs = pixel_values.shape[0]
297
+ print(f"dynamic ViT batch size: {image_bs}")
298
+
299
+ for num_patches in num_patches_list:
300
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
301
+ query = query.replace("<image>", image_tokens, 1)
302
+
303
+ print(query)
304
+ model_inputs = tokenizer(query, return_tensors="pt")
305
+ input_ids = model_inputs["input_ids"].to(self.device)
306
+ attention_mask = model_inputs["attention_mask"].to(self.device)
307
+ generation_config["eos_token_id"] = eos_token_id
308
+ generation_output = self.generate(
309
+ pixel_values=pixel_values, input_ids=input_ids, attention_mask=attention_mask, **generation_config
310
+ )
311
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
312
+ response = response.split(template.sep)[0].strip()
313
+ history.append((question, response))
314
+ if return_history:
315
+ return response, history
316
+ else:
317
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, "")
318
+ query_to_print = query_to_print.replace(f"{IMG_START_TOKEN}{IMG_END_TOKEN}", "<image>")
319
+ if verbose:
320
+ print(query_to_print, response)
321
+ return response
322
+
323
+ @torch.no_grad()
324
+ def generate(
325
+ self,
326
+ pixel_values: Optional[torch.FloatTensor] = None,
327
+ input_ids: Optional[torch.FloatTensor] = None,
328
+ attention_mask: Optional[torch.LongTensor] = None,
329
+ visual_features: Optional[torch.FloatTensor] = None,
330
+ generation_config: Optional[GenerationConfig] = None,
331
+ output_hidden_states: Optional[bool] = None,
332
+ return_dict: Optional[bool] = None,
333
+ **generate_kwargs,
334
+ ) -> torch.LongTensor:
335
+ assert self.img_context_token_id is not None
336
+ if pixel_values is not None:
337
+ if visual_features is not None:
338
+ vit_embeds = visual_features
339
+ else:
340
+ vit_embeds = self.extract_feature(pixel_values)
341
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
342
+ B, N, C = input_embeds.shape
343
+ input_embeds = input_embeds.reshape(B * N, C)
344
+
345
+ input_ids = input_ids.reshape(B * N)
346
+ selected = input_ids == self.img_context_token_id
347
+ assert selected.sum() != 0
348
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
349
+
350
+ input_embeds = input_embeds.reshape(B, N, C)
351
+ else:
352
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
353
+
354
+ outputs = self.language_model.generate(
355
+ inputs_embeds=input_embeds,
356
+ attention_mask=attention_mask,
357
+ generation_config=generation_config,
358
+ output_hidden_states=output_hidden_states,
359
+ return_dict=return_dict,
360
+ use_cache=True,
361
+ **generate_kwargs,
362
+ )
363
+
364
+ return outputs
preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": {
3
+ "height": 448,
4
+ "width": 448
5
+ },
6
+ "do_center_crop": true,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "image_mean": [
12
+ 0.485,
13
+ 0.456,
14
+ 0.406
15
+ ],
16
+ "image_processor_type": "CLIPFeatureExtractor",
17
+ "image_std": [
18
+ 0.229,
19
+ 0.224,
20
+ 0.225
21
+ ],
22
+ "resample": 3,
23
+ "rescale_factor": 0.00392156862745098,
24
+ "size": {
25
+ "shortest_edge": 28
26
+ }
27
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<img>",
6
+ "</img>",
7
+ "<IMG_CONTEXT>",
8
+ "<quad>",
9
+ "</quad>",
10
+ "<ref>",
11
+ "</ref>",
12
+ "<box>",
13
+ "</box>"
14
+ ],
15
+ "eos_token": {
16
+ "content": "<|im_end|>",
17
+ "lstrip": false,
18
+ "normalized": false,
19
+ "rstrip": false,
20
+ "single_word": false
21
+ },
22
+ "pad_token": {
23
+ "content": "<|endoftext|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false
28
+ }
29
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63a3df087afa0c8890b416fe2c4f3f2593f06181adda4aacf93db8eb34cf0208
3
+ size 11414752
tokenizer_config.json ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_eos_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": "<img>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "</img>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<IMG_CONTEXT>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<quad>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "</quad>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<ref>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "</ref>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<box>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "</box>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ }
101
+ },
102
+ "additional_special_tokens": [
103
+ "<|im_start|>",
104
+ "<|im_end|>",
105
+ "<img>",
106
+ "</img>",
107
+ "<IMG_CONTEXT>",
108
+ "<quad>",
109
+ "</quad>",
110
+ "<ref>",
111
+ "</ref>",
112
+ "<box>",
113
+ "</box>"
114
+ ],
115
+ "bos_token": null,
116
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
117
+ "clean_up_tokenization_spaces": false,
118
+ "eos_token": "<|im_end|>",
119
+ "errors": "replace",
120
+ "model_max_length": 8192,
121
+ "pad_token": "<|endoftext|>",
122
+ "split_special_tokens": false,
123
+ "tokenizer_class": "Qwen2Tokenizer",
124
+ "unk_token": null
125
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff