HumanBeauty commited on
Commit
1d8c741
·
verified ·
1 Parent(s): a24742e

Upload 17 files

Browse files
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,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "_name_or_path": "/home/zhengdezhi03/projects/Benchmark/models/HumanAesExpert-1B",
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": 448,
15
+ "hidden_size": 896,
16
+ "keys_to_ignore_at_inference": [
17
+ "past_key_values"
18
+ ],
19
+ "llm_config": {
20
+ "_name_or_path": "Qwen/Qwen2-0.5B-Instruct",
21
+ "add_cross_attention": false,
22
+ "architectures": [
23
+ "Qwen2ForCausalLM"
24
+ ],
25
+ "attention_dropout": 0.0,
26
+ "bad_words_ids": null,
27
+ "begin_suppress_tokens": null,
28
+ "bos_token_id": 151643,
29
+ "chunk_size_feed_forward": 0,
30
+ "cross_attention_hidden_size": null,
31
+ "decoder_start_token_id": null,
32
+ "diversity_penalty": 0.0,
33
+ "do_sample": false,
34
+ "early_stopping": false,
35
+ "encoder_no_repeat_ngram_size": 0,
36
+ "eos_token_id": 151645,
37
+ "exponential_decay_length_penalty": null,
38
+ "finetuning_task": null,
39
+ "forced_bos_token_id": null,
40
+ "forced_eos_token_id": null,
41
+ "hidden_act": "silu",
42
+ "hidden_size": 896,
43
+ "id2label": {
44
+ "0": "LABEL_0",
45
+ "1": "LABEL_1"
46
+ },
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 4864,
49
+ "is_decoder": false,
50
+ "is_encoder_decoder": false,
51
+ "label2id": {
52
+ "LABEL_0": 0,
53
+ "LABEL_1": 1
54
+ },
55
+ "length_penalty": 1.0,
56
+ "max_length": 20,
57
+ "max_position_embeddings": 32768,
58
+ "max_window_layers": 24,
59
+ "min_length": 0,
60
+ "model_type": "qwen2",
61
+ "no_repeat_ngram_size": 0,
62
+ "num_attention_heads": 14,
63
+ "num_beam_groups": 1,
64
+ "num_beams": 1,
65
+ "num_hidden_layers": 24,
66
+ "num_key_value_heads": 2,
67
+ "num_return_sequences": 1,
68
+ "output_attentions": false,
69
+ "output_hidden_states": false,
70
+ "output_scores": false,
71
+ "pad_token_id": null,
72
+ "prefix": null,
73
+ "problem_type": null,
74
+ "pruned_heads": {},
75
+ "remove_invalid_values": false,
76
+ "repetition_penalty": 1.0,
77
+ "return_dict": true,
78
+ "return_dict_in_generate": false,
79
+ "rms_norm_eps": 1e-06,
80
+ "rope_theta": 1000000.0,
81
+ "sep_token_id": null,
82
+ "sliding_window": null,
83
+ "suppress_tokens": null,
84
+ "task_specific_params": null,
85
+ "temperature": 1.0,
86
+ "tf_legacy_loss": false,
87
+ "tie_encoder_decoder": false,
88
+ "tie_word_embeddings": false,
89
+ "tokenizer_class": null,
90
+ "top_k": 50,
91
+ "top_p": 1.0,
92
+ "torch_dtype": "bfloat16",
93
+ "torchscript": false,
94
+ "transformers_version": "4.44.2",
95
+ "typical_p": 1.0,
96
+ "use_bfloat16": true,
97
+ "use_cache": true,
98
+ "use_sliding_window": false,
99
+ "vocab_size": 151655
100
+ },
101
+ "max_dynamic_patch": 12,
102
+ "min_dynamic_patch": 1,
103
+ "model_type": "internvl_chat",
104
+ "ps_version": "v2",
105
+ "select_layer": -1,
106
+ "template": "Hermes-2",
107
+ "torch_dtype": "float16",
108
+ "transformers_version": null,
109
+ "use_backbone_lora": 0,
110
+ "use_llm_lora": 0,
111
+ "use_thumbnail": true,
112
+ "vision_config": {
113
+ "_name_or_path": "",
114
+ "add_cross_attention": false,
115
+ "architectures": [
116
+ "InternVisionModel"
117
+ ],
118
+ "attention_dropout": 0.0,
119
+ "bad_words_ids": null,
120
+ "begin_suppress_tokens": null,
121
+ "bos_token_id": null,
122
+ "chunk_size_feed_forward": 0,
123
+ "cross_attention_hidden_size": null,
124
+ "decoder_start_token_id": null,
125
+ "diversity_penalty": 0.0,
126
+ "do_sample": false,
127
+ "drop_path_rate": 0.0,
128
+ "dropout": 0.0,
129
+ "early_stopping": false,
130
+ "encoder_no_repeat_ngram_size": 0,
131
+ "eos_token_id": null,
132
+ "exponential_decay_length_penalty": null,
133
+ "finetuning_task": null,
134
+ "forced_bos_token_id": null,
135
+ "forced_eos_token_id": null,
136
+ "hidden_act": "gelu",
137
+ "hidden_size": 1024,
138
+ "id2label": {
139
+ "0": "LABEL_0",
140
+ "1": "LABEL_1"
141
+ },
142
+ "image_size": 448,
143
+ "initializer_factor": 1.0,
144
+ "initializer_range": 0.02,
145
+ "intermediate_size": 4096,
146
+ "is_decoder": false,
147
+ "is_encoder_decoder": false,
148
+ "label2id": {
149
+ "LABEL_0": 0,
150
+ "LABEL_1": 1
151
+ },
152
+ "layer_norm_eps": 1e-06,
153
+ "length_penalty": 1.0,
154
+ "max_length": 20,
155
+ "min_length": 0,
156
+ "model_type": "intern_vit_6b",
157
+ "no_repeat_ngram_size": 0,
158
+ "norm_type": "layer_norm",
159
+ "num_attention_heads": 16,
160
+ "num_beam_groups": 1,
161
+ "num_beams": 1,
162
+ "num_channels": 3,
163
+ "num_hidden_layers": 24,
164
+ "num_return_sequences": 1,
165
+ "output_attentions": false,
166
+ "output_hidden_states": false,
167
+ "output_scores": false,
168
+ "pad_token_id": null,
169
+ "patch_size": 14,
170
+ "prefix": null,
171
+ "problem_type": null,
172
+ "pruned_heads": {},
173
+ "qk_normalization": false,
174
+ "qkv_bias": true,
175
+ "remove_invalid_values": false,
176
+ "repetition_penalty": 1.0,
177
+ "return_dict": true,
178
+ "return_dict_in_generate": false,
179
+ "sep_token_id": null,
180
+ "suppress_tokens": null,
181
+ "task_specific_params": null,
182
+ "temperature": 1.0,
183
+ "tf_legacy_loss": false,
184
+ "tie_encoder_decoder": false,
185
+ "tie_word_embeddings": true,
186
+ "tokenizer_class": null,
187
+ "top_k": 50,
188
+ "top_p": 1.0,
189
+ "torch_dtype": "bfloat16",
190
+ "torchscript": false,
191
+ "transformers_version": "4.44.2",
192
+ "typical_p": 1.0,
193
+ "use_bfloat16": true,
194
+ "use_flash_attn": false
195
+ }
196
+ }
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
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
+
7
+ import os
8
+ from typing import Union
9
+
10
+ from transformers.configuration_utils import PretrainedConfig
11
+ from transformers.utils import logging
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,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 AutoConfig, 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
+ logger = logging.get_logger(__name__)
16
+
17
+
18
+ class InternVLChatConfig(PretrainedConfig):
19
+ model_type = 'internvl_chat'
20
+ is_composition = True
21
+
22
+ def __init__(
23
+ self,
24
+ vision_config=None,
25
+ llm_config=None,
26
+ use_backbone_lora=0,
27
+ use_llm_lora=0,
28
+ select_layer=-1,
29
+ force_image_size=None,
30
+ downsample_ratio=0.5,
31
+ template=None,
32
+ dynamic_image_size=False,
33
+ use_thumbnail=False,
34
+ ps_version='v1',
35
+ min_dynamic_patch=1,
36
+ max_dynamic_patch=6,
37
+ **kwargs):
38
+ super().__init__(**kwargs)
39
+
40
+ if vision_config is None:
41
+ vision_config = {'architectures': ['InternVisionModel']}
42
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
43
+
44
+ if llm_config is None:
45
+ llm_config = {'architectures': ['Qwen2ForCausalLM']}
46
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
47
+
48
+ self.vision_config = InternVisionConfig(**vision_config)
49
+ if llm_config.get('architectures')[0] == 'LlamaForCausalLM':
50
+ self.llm_config = LlamaConfig(**llm_config)
51
+ elif llm_config.get('architectures')[0] == 'Qwen2ForCausalLM':
52
+ self.llm_config = Qwen2Config(**llm_config)
53
+ else:
54
+ raise ValueError('Unsupported architecture: {}'.format(llm_config.get('architectures')[0]))
55
+ self.use_backbone_lora = use_backbone_lora
56
+ self.use_llm_lora = use_llm_lora
57
+ self.select_layer = select_layer
58
+ self.force_image_size = force_image_size
59
+ self.downsample_ratio = downsample_ratio
60
+ self.template = template
61
+ self.dynamic_image_size = dynamic_image_size
62
+ self.use_thumbnail = use_thumbnail
63
+ self.ps_version = ps_version # pixel shuffle version
64
+ self.min_dynamic_patch = min_dynamic_patch
65
+ self.max_dynamic_patch = max_dynamic_patch
66
+
67
+ logger.info(f'vision_select_layer: {self.select_layer}')
68
+ logger.info(f'ps_version: {self.ps_version}')
69
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
70
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
71
+
72
+ def to_dict(self):
73
+ """
74
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
75
+
76
+ Returns:
77
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
78
+ """
79
+ output = copy.deepcopy(self.__dict__)
80
+ output['vision_config'] = self.vision_config.to_dict()
81
+ output['llm_config'] = self.llm_config.to_dict()
82
+ output['model_type'] = self.__class__.model_type
83
+ output['use_backbone_lora'] = self.use_backbone_lora
84
+ output['use_llm_lora'] = self.use_llm_lora
85
+ output['select_layer'] = self.select_layer
86
+ output['force_image_size'] = self.force_image_size
87
+ output['downsample_ratio'] = self.downsample_ratio
88
+ output['template'] = self.template
89
+ output['dynamic_image_size'] = self.dynamic_image_size
90
+ output['use_thumbnail'] = self.use_thumbnail
91
+ output['ps_version'] = self.ps_version
92
+ output['min_dynamic_patch'] = self.min_dynamic_patch
93
+ output['max_dynamic_patch'] = self.max_dynamic_patch
94
+
95
+ return output
conversation.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Modified from https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
8
+ """
9
+
10
+ import dataclasses
11
+ from enum import IntEnum, auto
12
+ from typing import Dict, List, Tuple, Union
13
+
14
+
15
+ class SeparatorStyle(IntEnum):
16
+ """Separator styles."""
17
+
18
+ ADD_COLON_SINGLE = auto()
19
+ ADD_COLON_TWO = auto()
20
+ ADD_COLON_SPACE_SINGLE = auto()
21
+ NO_COLON_SINGLE = auto()
22
+ NO_COLON_TWO = auto()
23
+ ADD_NEW_LINE_SINGLE = auto()
24
+ LLAMA2 = auto()
25
+ CHATGLM = auto()
26
+ CHATML = auto()
27
+ CHATINTERN = auto()
28
+ DOLLY = auto()
29
+ RWKV = auto()
30
+ PHOENIX = auto()
31
+ ROBIN = auto()
32
+ FALCON_CHAT = auto()
33
+ CHATGLM3 = auto()
34
+ INTERNVL_ZH = auto()
35
+ MPT = auto()
36
+
37
+
38
+ @dataclasses.dataclass
39
+ class Conversation:
40
+ """A class that manages prompt templates and keeps all conversation history."""
41
+
42
+ # The name of this template
43
+ name: str
44
+ # The template of the system prompt
45
+ system_template: str = '{system_message}'
46
+ # The system message
47
+ system_message: str = ''
48
+ # The names of two roles
49
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
50
+ # All messages. Each item is (role, message).
51
+ messages: List[List[str]] = ()
52
+ # The number of few shot examples
53
+ offset: int = 0
54
+ # The separator style and configurations
55
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
56
+ sep: str = '\n'
57
+ sep2: str = None
58
+ # Stop criteria (the default one is EOS token)
59
+ stop_str: Union[str, List[str]] = None
60
+ # Stops generation if meeting any token in this list
61
+ stop_token_ids: List[int] = None
62
+
63
+ def get_prompt(self) -> str:
64
+ """Get the prompt for generation."""
65
+ system_prompt = self.system_template.format(system_message=self.system_message)
66
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
67
+ ret = system_prompt + self.sep
68
+ for role, message in self.messages:
69
+ if message:
70
+ ret += role + ': ' + message + self.sep
71
+ else:
72
+ ret += role + ':'
73
+ return ret
74
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
75
+ seps = [self.sep, self.sep2]
76
+ ret = system_prompt + seps[0]
77
+ for i, (role, message) in enumerate(self.messages):
78
+ if message:
79
+ ret += role + ': ' + message + seps[i % 2]
80
+ else:
81
+ ret += role + ':'
82
+ return ret
83
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
84
+ ret = system_prompt + self.sep
85
+ for role, message in self.messages:
86
+ if message:
87
+ ret += role + ': ' + message + self.sep
88
+ else:
89
+ ret += role + ': ' # must be end with a space
90
+ return ret
91
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
92
+ ret = '' if system_prompt == '' else system_prompt + self.sep
93
+ for role, message in self.messages:
94
+ if message:
95
+ ret += role + '\n' + message + self.sep
96
+ else:
97
+ ret += role + '\n'
98
+ return ret
99
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
100
+ ret = system_prompt
101
+ for role, message in self.messages:
102
+ if message:
103
+ ret += role + message + self.sep
104
+ else:
105
+ ret += role
106
+ return ret
107
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
108
+ seps = [self.sep, self.sep2]
109
+ ret = system_prompt
110
+ for i, (role, message) in enumerate(self.messages):
111
+ if message:
112
+ ret += role + message + seps[i % 2]
113
+ else:
114
+ ret += role
115
+ return ret
116
+ elif self.sep_style == SeparatorStyle.RWKV:
117
+ ret = system_prompt
118
+ for i, (role, message) in enumerate(self.messages):
119
+ if message:
120
+ ret += (
121
+ role
122
+ + ': '
123
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
124
+ )
125
+ ret += '\n\n'
126
+ else:
127
+ ret += role + ':'
128
+ return ret
129
+ elif self.sep_style == SeparatorStyle.LLAMA2:
130
+ seps = [self.sep, self.sep2]
131
+ if self.system_message:
132
+ ret = system_prompt
133
+ else:
134
+ ret = '[INST] '
135
+ for i, (role, message) in enumerate(self.messages):
136
+ tag = self.roles[i % 2]
137
+ if message:
138
+ if i == 0:
139
+ ret += message + ' '
140
+ else:
141
+ ret += tag + ' ' + message + seps[i % 2]
142
+ else:
143
+ ret += tag
144
+ return ret
145
+ elif self.sep_style == SeparatorStyle.CHATGLM:
146
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
147
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
148
+ round_add_n = 1 if self.name == 'chatglm2' else 0
149
+ if system_prompt:
150
+ ret = system_prompt + self.sep
151
+ else:
152
+ ret = ''
153
+
154
+ for i, (role, message) in enumerate(self.messages):
155
+ if i % 2 == 0:
156
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
157
+
158
+ if message:
159
+ ret += f'{role}:{message}{self.sep}'
160
+ else:
161
+ ret += f'{role}:'
162
+ return ret
163
+ elif self.sep_style == SeparatorStyle.CHATML:
164
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
165
+ for role, message in self.messages:
166
+ if message:
167
+ ret += role + '\n' + message + self.sep + '\n'
168
+ else:
169
+ ret += role + '\n'
170
+ return ret
171
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
172
+ ret = ''
173
+ if self.system_message:
174
+ ret += system_prompt
175
+ for role, message in self.messages:
176
+ if message:
177
+ ret += role + '\n' + ' ' + message
178
+ else:
179
+ ret += role
180
+ return ret
181
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
182
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
183
+ seps = [self.sep, self.sep2]
184
+ ret = system_prompt
185
+ for i, (role, message) in enumerate(self.messages):
186
+ # if i % 2 == 0:
187
+ # ret += "<s>"
188
+ if message:
189
+ ret += role + ':' + message + seps[i % 2] + '\n'
190
+ else:
191
+ ret += role + ':'
192
+ return ret
193
+ elif self.sep_style == SeparatorStyle.DOLLY:
194
+ seps = [self.sep, self.sep2]
195
+ ret = system_prompt
196
+ for i, (role, message) in enumerate(self.messages):
197
+ if message:
198
+ ret += role + ':\n' + message + seps[i % 2]
199
+ if i % 2 == 1:
200
+ ret += '\n\n'
201
+ else:
202
+ ret += role + ':\n'
203
+ return ret
204
+ elif self.sep_style == SeparatorStyle.PHOENIX:
205
+ ret = system_prompt
206
+ for role, message in self.messages:
207
+ if message:
208
+ ret += role + ': ' + '<s>' + message + '</s>'
209
+ else:
210
+ ret += role + ': ' + '<s>'
211
+ return ret
212
+ elif self.sep_style == SeparatorStyle.ROBIN:
213
+ ret = system_prompt + self.sep
214
+ for role, message in self.messages:
215
+ if message:
216
+ ret += role + ':\n' + message + self.sep
217
+ else:
218
+ ret += role + ':\n'
219
+ return ret
220
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
221
+ ret = ''
222
+ if self.system_message:
223
+ ret += system_prompt + self.sep
224
+ for role, message in self.messages:
225
+ if message:
226
+ ret += role + ': ' + message + self.sep
227
+ else:
228
+ ret += role + ':'
229
+
230
+ return ret
231
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
232
+ seps = [self.sep, self.sep2]
233
+ ret = self.system_message + seps[0]
234
+ for i, (role, message) in enumerate(self.messages):
235
+ if message:
236
+ ret += role + ': ' + message + seps[i % 2]
237
+ else:
238
+ ret += role + ':'
239
+ return ret
240
+ elif self.sep_style == SeparatorStyle.MPT:
241
+ ret = system_prompt + self.sep
242
+ for role, message in self.messages:
243
+ if message:
244
+ if type(message) is tuple:
245
+ message, _, _ = message
246
+ ret += role + message + self.sep
247
+ else:
248
+ ret += role
249
+ return ret
250
+ else:
251
+ raise ValueError(f'Invalid style: {self.sep_style}')
252
+
253
+ def set_system_message(self, system_message: str):
254
+ """Set the system message."""
255
+ self.system_message = system_message
256
+
257
+ def append_message(self, role: str, message: str):
258
+ """Append a new message."""
259
+ self.messages.append([role, message])
260
+
261
+ def update_last_message(self, message: str):
262
+ """Update the last output.
263
+
264
+ The last message is typically set to be None when constructing the prompt,
265
+ so we need to update it in-place after getting the response from a model.
266
+ """
267
+ self.messages[-1][1] = message
268
+
269
+ def to_gradio_chatbot(self):
270
+ """Convert the conversation to gradio chatbot format."""
271
+ ret = []
272
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
273
+ if i % 2 == 0:
274
+ ret.append([msg, None])
275
+ else:
276
+ ret[-1][-1] = msg
277
+ return ret
278
+
279
+ def to_openai_api_messages(self):
280
+ """Convert the conversation to OpenAI chat completion format."""
281
+ ret = [{'role': 'system', 'content': self.system_message}]
282
+
283
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
284
+ if i % 2 == 0:
285
+ ret.append({'role': 'user', 'content': msg})
286
+ else:
287
+ if msg is not None:
288
+ ret.append({'role': 'assistant', 'content': msg})
289
+ return ret
290
+
291
+ def copy(self):
292
+ return Conversation(
293
+ name=self.name,
294
+ system_template=self.system_template,
295
+ system_message=self.system_message,
296
+ roles=self.roles,
297
+ messages=[[x, y] for x, y in self.messages],
298
+ offset=self.offset,
299
+ sep_style=self.sep_style,
300
+ sep=self.sep,
301
+ sep2=self.sep2,
302
+ stop_str=self.stop_str,
303
+ stop_token_ids=self.stop_token_ids,
304
+ )
305
+
306
+ def dict(self):
307
+ return {
308
+ 'template_name': self.name,
309
+ 'system_message': self.system_message,
310
+ 'roles': self.roles,
311
+ 'messages': self.messages,
312
+ 'offset': self.offset,
313
+ }
314
+
315
+
316
+ # A global registry for all conversation templates
317
+ conv_templates: Dict[str, Conversation] = {}
318
+
319
+
320
+ def register_conv_template(template: Conversation, override: bool = False):
321
+ """Register a new conversation template."""
322
+ if not override:
323
+ assert (
324
+ template.name not in conv_templates
325
+ ), f'{template.name} has been registered.'
326
+
327
+ conv_templates[template.name] = template
328
+
329
+
330
+ def get_conv_template(name: str) -> Conversation:
331
+ """Get a conversation template."""
332
+ return conv_templates[name].copy()
333
+
334
+
335
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
336
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
337
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
338
+ # Therefore, they are completely equivalent during inference.
339
+ register_conv_template(
340
+ Conversation(
341
+ name='Hermes-2',
342
+ system_template='<|im_start|>system\n{system_message}',
343
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
344
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
345
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
346
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
347
+ sep_style=SeparatorStyle.MPT,
348
+ sep='<|im_end|>',
349
+ stop_str='<|endoftext|>',
350
+ )
351
+ )
352
+
353
+
354
+ register_conv_template(
355
+ Conversation(
356
+ name='internlm2-chat',
357
+ system_template='<|im_start|>system\n{system_message}',
358
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
359
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
360
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
361
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
362
+ sep_style=SeparatorStyle.MPT,
363
+ sep='<|im_end|>',
364
+ )
365
+ )
366
+
367
+
368
+ register_conv_template(
369
+ Conversation(
370
+ name='phi3-chat',
371
+ system_template='<|system|>\n{system_message}',
372
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
373
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
374
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
375
+ roles=('<|user|>\n', '<|assistant|>\n'),
376
+ sep_style=SeparatorStyle.MPT,
377
+ sep='<|end|>',
378
+ )
379
+ )
380
+
381
+
382
+ register_conv_template(
383
+ Conversation(
384
+ name='internvl2_5',
385
+ system_template='<|im_start|>system\n{system_message}',
386
+ system_message='你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
387
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
388
+ sep_style=SeparatorStyle.MPT,
389
+ sep='<|im_end|>\n',
390
+ )
391
+ )
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "eos_token_id": 151645,
3
+ "max_new_tokens": 2048,
4
+ "pad_token_id": 151643,
5
+ "transformers_version": "4.44.2"
6
+ }
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:2b40d143fc5fd4a04c10781740d39615af3549555e7c40c05834d08a826ed64e
3
+ size 1876417886
modeling_intern_vit.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
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
+ try:
24
+ from flash_attn.bert_padding import pad_input, unpad_input
25
+ from flash_attn.flash_attn_interface import \
26
+ flash_attn_varlen_qkvpacked_func
27
+ has_flash_attn = True
28
+ except:
29
+ print('FlashAttention2 is not installed.')
30
+ has_flash_attn = False
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ class FlashAttention(nn.Module):
36
+ """Implement the scaled dot product attention with softmax.
37
+ Arguments
38
+ ---------
39
+ softmax_scale: The temperature to use for the softmax attention.
40
+ (default: 1/sqrt(d_keys) where d_keys is computed at
41
+ runtime)
42
+ attention_dropout: The dropout rate to apply to the attention
43
+ (default: 0.0)
44
+ """
45
+
46
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
47
+ super().__init__()
48
+ self.softmax_scale = softmax_scale
49
+ self.dropout_p = attention_dropout
50
+
51
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
52
+ max_s=None, need_weights=False):
53
+ """Implements the multihead softmax attention.
54
+ Arguments
55
+ ---------
56
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
57
+ if unpadded: (nnz, 3, h, d)
58
+ key_padding_mask: a bool tensor of shape (B, S)
59
+ """
60
+ assert not need_weights
61
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
62
+ assert qkv.is_cuda
63
+
64
+ if cu_seqlens is None:
65
+ batch_size = qkv.shape[0]
66
+ seqlen = qkv.shape[1]
67
+ if key_padding_mask is None:
68
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
69
+ max_s = seqlen
70
+ cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
71
+ device=qkv.device)
72
+ output = flash_attn_varlen_qkvpacked_func(
73
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
74
+ softmax_scale=self.softmax_scale, causal=causal
75
+ )
76
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
77
+ else:
78
+ nheads = qkv.shape[-2]
79
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
80
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
81
+ x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
82
+ output_unpad = flash_attn_varlen_qkvpacked_func(
83
+ x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
84
+ softmax_scale=self.softmax_scale, causal=causal
85
+ )
86
+ output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
87
+ indices, batch_size, seqlen),
88
+ 'b s (h d) -> b s h d', h=nheads)
89
+ else:
90
+ assert max_s is not None
91
+ output = flash_attn_varlen_qkvpacked_func(
92
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
93
+ softmax_scale=self.softmax_scale, causal=causal
94
+ )
95
+
96
+ return output, None
97
+
98
+
99
+ class InternRMSNorm(nn.Module):
100
+ def __init__(self, hidden_size, eps=1e-6):
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ input_dtype = hidden_states.dtype
107
+ hidden_states = hidden_states.to(torch.float32)
108
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
109
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
110
+ return self.weight * hidden_states.to(input_dtype)
111
+
112
+
113
+ try:
114
+ from apex.normalization import FusedRMSNorm
115
+
116
+ InternRMSNorm = FusedRMSNorm # noqa
117
+
118
+ logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
119
+ except ImportError:
120
+ # using the normal InternRMSNorm
121
+ pass
122
+ except Exception:
123
+ logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
124
+ pass
125
+
126
+
127
+ NORM2FN = {
128
+ 'rms_norm': InternRMSNorm,
129
+ 'layer_norm': nn.LayerNorm,
130
+ }
131
+
132
+
133
+ class InternVisionEmbeddings(nn.Module):
134
+ def __init__(self, config: InternVisionConfig):
135
+ super().__init__()
136
+ self.config = config
137
+ self.embed_dim = config.hidden_size
138
+ self.image_size = config.image_size
139
+ self.patch_size = config.patch_size
140
+
141
+ self.class_embedding = nn.Parameter(
142
+ torch.randn(1, 1, self.embed_dim),
143
+ )
144
+
145
+ self.patch_embedding = nn.Conv2d(
146
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
147
+ )
148
+
149
+ self.num_patches = (self.image_size // self.patch_size) ** 2
150
+ self.num_positions = self.num_patches + 1
151
+
152
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
153
+
154
+ def _get_pos_embed(self, pos_embed, H, W):
155
+ target_dtype = pos_embed.dtype
156
+ pos_embed = pos_embed.float().reshape(
157
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
158
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
159
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
160
+ return pos_embed
161
+
162
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
163
+ target_dtype = self.patch_embedding.weight.dtype
164
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
165
+ batch_size, _, height, width = patch_embeds.shape
166
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
167
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
168
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
169
+ position_embedding = torch.cat([
170
+ self.position_embedding[:, :1, :],
171
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
172
+ ], dim=1)
173
+ embeddings = embeddings + position_embedding.to(target_dtype)
174
+ return embeddings
175
+
176
+
177
+ class InternAttention(nn.Module):
178
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
179
+
180
+ def __init__(self, config: InternVisionConfig):
181
+ super().__init__()
182
+ self.config = config
183
+ self.embed_dim = config.hidden_size
184
+ self.num_heads = config.num_attention_heads
185
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
186
+ if config.use_flash_attn and not has_flash_attn:
187
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
188
+ self.head_dim = self.embed_dim // self.num_heads
189
+ if self.head_dim * self.num_heads != self.embed_dim:
190
+ raise ValueError(
191
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
192
+ f' {self.num_heads}).'
193
+ )
194
+
195
+ self.scale = self.head_dim ** -0.5
196
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
197
+ self.attn_drop = nn.Dropout(config.attention_dropout)
198
+ self.proj_drop = nn.Dropout(config.dropout)
199
+
200
+ self.qk_normalization = config.qk_normalization
201
+
202
+ if self.qk_normalization:
203
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
204
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
205
+
206
+ if self.use_flash_attn:
207
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
208
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
209
+
210
+ def _naive_attn(self, x):
211
+ B, N, C = x.shape
212
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
213
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
214
+
215
+ if self.qk_normalization:
216
+ B_, H_, N_, D_ = q.shape
217
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
218
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
219
+
220
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
221
+ attn = attn.softmax(dim=-1)
222
+ attn = self.attn_drop(attn)
223
+
224
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
225
+ x = self.proj(x)
226
+ x = self.proj_drop(x)
227
+ return x
228
+
229
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
230
+ qkv = self.qkv(x)
231
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
232
+
233
+ if self.qk_normalization:
234
+ q, k, v = qkv.unbind(2)
235
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
236
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
237
+ qkv = torch.stack([q, k, v], dim=2)
238
+
239
+ context, _ = self.inner_attn(
240
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
241
+ )
242
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
243
+ outs = self.proj_drop(outs)
244
+ return outs
245
+
246
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
247
+ x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
248
+ return x
249
+
250
+
251
+ class InternMLP(nn.Module):
252
+ def __init__(self, config: InternVisionConfig):
253
+ super().__init__()
254
+ self.config = config
255
+ self.act = ACT2FN[config.hidden_act]
256
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
257
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
258
+
259
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
260
+ hidden_states = self.fc1(hidden_states)
261
+ hidden_states = self.act(hidden_states)
262
+ hidden_states = self.fc2(hidden_states)
263
+ return hidden_states
264
+
265
+
266
+ class InternVisionEncoderLayer(nn.Module):
267
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
268
+ super().__init__()
269
+ self.embed_dim = config.hidden_size
270
+ self.intermediate_size = config.intermediate_size
271
+ self.norm_type = config.norm_type
272
+
273
+ self.attn = InternAttention(config)
274
+ self.mlp = InternMLP(config)
275
+ self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
276
+ self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
277
+
278
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
279
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
280
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
281
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
282
+
283
+ def forward(
284
+ self,
285
+ hidden_states: torch.Tensor,
286
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
287
+ """
288
+ Args:
289
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
290
+ """
291
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states).to(hidden_states.dtype)) * self.ls1)
292
+
293
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states).to(hidden_states.dtype)) * self.ls2)
294
+
295
+ return hidden_states
296
+
297
+
298
+ class InternVisionEncoder(nn.Module):
299
+ """
300
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
301
+ [`InternEncoderLayer`].
302
+
303
+ Args:
304
+ config (`InternConfig`):
305
+ The corresponding vision configuration for the `InternEncoder`.
306
+ """
307
+
308
+ def __init__(self, config: InternVisionConfig):
309
+ super().__init__()
310
+ self.config = config
311
+ # stochastic depth decay rule
312
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
313
+ self.layers = nn.ModuleList([
314
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
315
+ self.gradient_checkpointing = True
316
+
317
+ def forward(
318
+ self,
319
+ inputs_embeds,
320
+ output_hidden_states: Optional[bool] = None,
321
+ return_dict: Optional[bool] = None,
322
+ ) -> Union[Tuple, BaseModelOutput]:
323
+ r"""
324
+ Args:
325
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
326
+ Embedded representation of the inputs. Should be float, not int tokens.
327
+ output_hidden_states (`bool`, *optional*):
328
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
329
+ for more detail.
330
+ return_dict (`bool`, *optional*):
331
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
332
+ """
333
+ output_hidden_states = (
334
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
335
+ )
336
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
337
+
338
+ encoder_states = () if output_hidden_states else None
339
+ hidden_states = inputs_embeds
340
+
341
+ for idx, encoder_layer in enumerate(self.layers):
342
+ if output_hidden_states:
343
+ encoder_states = encoder_states + (hidden_states,)
344
+ if self.gradient_checkpointing and self.training:
345
+ layer_outputs = torch.utils.checkpoint.checkpoint(
346
+ encoder_layer,
347
+ hidden_states)
348
+ else:
349
+ layer_outputs = encoder_layer(
350
+ hidden_states,
351
+ )
352
+ hidden_states = layer_outputs
353
+
354
+ if output_hidden_states:
355
+ encoder_states = encoder_states + (hidden_states,)
356
+
357
+ if not return_dict:
358
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
359
+ return BaseModelOutput(
360
+ last_hidden_state=hidden_states, hidden_states=encoder_states
361
+ )
362
+
363
+
364
+ class InternVisionModel(PreTrainedModel):
365
+ main_input_name = 'pixel_values'
366
+ _supports_flash_attn_2 = True
367
+ config_class = InternVisionConfig
368
+ _no_split_modules = ['InternVisionEncoderLayer']
369
+
370
+ def __init__(self, config: InternVisionConfig):
371
+ super().__init__(config)
372
+ self.config = config
373
+
374
+ self.embeddings = InternVisionEmbeddings(config)
375
+ self.encoder = InternVisionEncoder(config)
376
+
377
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
378
+ pos_emb = self.embeddings.position_embedding
379
+ _, num_positions, embed_dim = pos_emb.shape
380
+ cls_emb = pos_emb[:, :1, :]
381
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
382
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
383
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
384
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
385
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
386
+ self.embeddings.image_size = new_size
387
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
388
+
389
+ def get_input_embeddings(self):
390
+ return self.embeddings
391
+
392
+ def forward(
393
+ self,
394
+ pixel_values: Optional[torch.FloatTensor] = None,
395
+ output_hidden_states: Optional[bool] = None,
396
+ return_dict: Optional[bool] = None,
397
+ pixel_embeds: Optional[torch.FloatTensor] = None,
398
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
399
+ output_hidden_states = (
400
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
401
+ )
402
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
403
+
404
+ if pixel_values is None and pixel_embeds is None:
405
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
406
+
407
+ if pixel_embeds is not None:
408
+ hidden_states = pixel_embeds
409
+ else:
410
+ if len(pixel_values.shape) == 4:
411
+ hidden_states = self.embeddings(pixel_values)
412
+ else:
413
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
414
+ encoder_outputs = self.encoder(
415
+ inputs_embeds=hidden_states,
416
+ output_hidden_states=output_hidden_states,
417
+ return_dict=return_dict,
418
+ )
419
+ last_hidden_state = encoder_outputs.last_hidden_state
420
+ pooled_output = last_hidden_state[:, 0, :]
421
+
422
+ if not return_dict:
423
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
424
+
425
+ return BaseModelOutputWithPooling(
426
+ last_hidden_state=last_hidden_state,
427
+ pooler_output=pooled_output,
428
+ hidden_states=encoder_outputs.hidden_states,
429
+ attentions=encoder_outputs.attentions,
430
+ )
modeling_internvl_chat.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Any, 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 (AutoModel, GenerationConfig, LlamaForCausalLM,)
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.utils import ModelOutput, logging
16
+
17
+ from .configuration_internvl_chat import InternVLChatConfig
18
+ from .conversation import get_conv_template
19
+ from .modeling_intern_vit import InternVisionModel, has_flash_attn
20
+ from .modeling_qwen import Qwen2ForCausalLM_score, CausalLMOutputWithPastAndScore
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ special_words = ["excellent","good","fair","poor","bad"]
25
+ weight_tensor = torch.Tensor([5.,4.,3.,2.,1.])
26
+
27
+ def get_special_token(tokenizer):
28
+ preferential_ids_ = [id_[-1] for id_ in tokenizer(special_words)["input_ids"]]
29
+ print(preferential_ids_)
30
+ print(tokenizer.batch_decode(preferential_ids_))
31
+ return preferential_ids_
32
+
33
+
34
+ def get_probs(logits, special_tokens_ids, way='softmax'):
35
+ target_logits = []
36
+ for idx in special_tokens_ids:
37
+ target_logits.append(torch.sum(logits[idx]))
38
+ target_logits = torch.tensor(target_logits)
39
+ if way == 'linear':
40
+ target_logits /= torch.sum(target_logits)
41
+ elif way == 'softmax': # q-align
42
+ target_logits = torch.softmax(target_logits, dim=-1)
43
+ score = target_logits @ weight_tensor.to(dtype=target_logits.dtype)
44
+ score -= torch.min(weight_tensor)
45
+ score /= torch.max(weight_tensor - torch.min(weight_tensor))
46
+ return float(score)
47
+
48
+ def version_cmp(v1, v2, op='eq'):
49
+ import operator
50
+
51
+ from packaging import version
52
+ op_func = getattr(operator, op)
53
+ return op_func(version.parse(v1), version.parse(v2))
54
+
55
+
56
+ class InternVLChatModel(PreTrainedModel):
57
+ config_class = InternVLChatConfig
58
+ main_input_name = 'pixel_values'
59
+ base_model_prefix = 'language_model'
60
+ _supports_flash_attn_2 = True
61
+ _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'Qwen2DecoderLayer']
62
+
63
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
64
+ super().__init__(config)
65
+
66
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
67
+ image_size = config.force_image_size or config.vision_config.image_size
68
+ patch_size = config.vision_config.patch_size
69
+ self.patch_size = patch_size
70
+ self.select_layer = config.select_layer
71
+ self.template = config.template
72
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
73
+ self.downsample_ratio = config.downsample_ratio
74
+ self.ps_version = config.ps_version
75
+ use_flash_attn = use_flash_attn if has_flash_attn else False
76
+ config.vision_config.use_flash_attn = True if use_flash_attn else False
77
+ config.llm_config._attn_implementation = 'flash_attention_2' if use_flash_attn else 'eager'
78
+
79
+ logger.info(f'num_image_token: {self.num_image_token}')
80
+ logger.info(f'ps_version: {self.ps_version}')
81
+ if vision_model is not None:
82
+ self.vision_model = vision_model
83
+ else:
84
+ self.vision_model = InternVisionModel(config.vision_config)
85
+ if language_model is not None:
86
+ self.language_model = language_model
87
+ else:
88
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
89
+ self.language_model = LlamaForCausalLM(config.llm_config)
90
+ elif config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
91
+ self.language_model = Qwen2ForCausalLM_score(config.llm_config)
92
+ else:
93
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
94
+
95
+ vit_hidden_size = config.vision_config.hidden_size
96
+ llm_hidden_size = config.llm_config.hidden_size
97
+
98
+ self.mlp1 = nn.Sequential(
99
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
100
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
101
+ nn.GELU(),
102
+ nn.Linear(llm_hidden_size, llm_hidden_size)
103
+ )
104
+
105
+ self.metavoter = nn.Sequential(
106
+ nn.Linear(3, 8),
107
+ nn.BatchNorm1d(8),
108
+ nn.ReLU(),
109
+ nn.Linear(8, 8),
110
+ nn.BatchNorm1d(8),
111
+ nn.ReLU(),
112
+ nn.Linear(8, 1)
113
+ )
114
+ self.special_tokens = None
115
+
116
+ self.img_context_token_id = None
117
+ self.conv_template = get_conv_template(self.template)
118
+ self.system_message = self.conv_template.system_message
119
+
120
+ def forward(
121
+ self,
122
+ pixel_values: torch.FloatTensor,
123
+ input_ids: torch.LongTensor = None,
124
+ attention_mask: Optional[torch.Tensor] = None,
125
+ position_ids: Optional[torch.LongTensor] = None,
126
+ image_flags: Optional[torch.LongTensor] = None,
127
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
128
+ labels: Optional[torch.LongTensor] = None,
129
+ use_cache: Optional[bool] = None,
130
+ output_attentions: Optional[bool] = None,
131
+ output_hidden_states: Optional[bool] = None,
132
+ return_dict: Optional[bool] = None,
133
+ ) -> Union[Tuple, CausalLMOutputWithPastAndScore]:
134
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
135
+
136
+ image_flags = image_flags.squeeze(-1)
137
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
138
+
139
+ vit_embeds = self.extract_feature(pixel_values)
140
+ vit_embeds = vit_embeds[image_flags == 1]
141
+ vit_batch_size = pixel_values.shape[0]
142
+
143
+ B, N, C = input_embeds.shape
144
+ input_embeds = input_embeds.reshape(B * N, C)
145
+
146
+ try:
147
+ if torch.distributed.get_rank() == 0:
148
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
149
+ except:
150
+ pass
151
+
152
+ input_ids = input_ids.reshape(B * N)
153
+ selected = (input_ids == self.img_context_token_id)
154
+ try:
155
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
156
+ except Exception as e:
157
+ vit_embeds = vit_embeds.reshape(-1, C)
158
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
159
+ f'vit_embeds.shape={vit_embeds.shape}')
160
+ n_token = selected.sum()
161
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
162
+
163
+ input_embeds = input_embeds.reshape(B, N, C)
164
+
165
+ outputs = self.language_model(
166
+ inputs_embeds=input_embeds,
167
+ attention_mask=attention_mask,
168
+ position_ids=position_ids,
169
+ past_key_values=past_key_values,
170
+ use_cache=use_cache,
171
+ output_attentions=output_attentions,
172
+ output_hidden_states=output_hidden_states,
173
+ return_dict=return_dict,
174
+ )
175
+ logits = outputs.logits
176
+ scores = outputs.scores
177
+ experts_scores = outputs.experts_scores
178
+
179
+ loss = None
180
+ if labels is not None:
181
+ # Shift so that tokens < n predict n
182
+ shift_logits = logits[..., :-1, :].contiguous()
183
+ shift_labels = labels[..., 1:].contiguous()
184
+ # Flatten the tokens
185
+ loss_fct = CrossEntropyLoss()
186
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
187
+ shift_labels = shift_labels.view(-1)
188
+ # Enable model parallelism
189
+ shift_labels = shift_labels.to(shift_logits.device)
190
+ loss = loss_fct(shift_logits, shift_labels)
191
+
192
+ if not return_dict:
193
+ output = (logits,) + outputs[1:]
194
+ return (loss,) + output if loss is not None else output
195
+
196
+ return CausalLMOutputWithPastAndScore(
197
+ loss=loss,
198
+ logits=logits,
199
+ scores=scores,
200
+ experts_scores=experts_scores,
201
+ past_key_values=outputs.past_key_values,
202
+ hidden_states=outputs.hidden_states,
203
+ attentions=outputs.attentions,
204
+ )
205
+
206
+ def pixel_shuffle(self, x, scale_factor=0.5):
207
+ n, w, h, c = x.size()
208
+ # N, W, H, C --> N, W, H * scale, C // scale
209
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
210
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
211
+ x = x.permute(0, 2, 1, 3).contiguous()
212
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
213
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
214
+ int(c / (scale_factor * scale_factor)))
215
+ if self.ps_version == 'v1':
216
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
217
+ 'which results in a transposed image.')
218
+ else:
219
+ x = x.permute(0, 2, 1, 3).contiguous()
220
+ return x
221
+
222
+ def extract_feature(self, pixel_values):
223
+ if self.select_layer == -1:
224
+ vit_embeds = self.vision_model(
225
+ pixel_values=pixel_values,
226
+ output_hidden_states=False,
227
+ return_dict=True).last_hidden_state
228
+ else:
229
+ vit_embeds = self.vision_model(
230
+ pixel_values=pixel_values,
231
+ output_hidden_states=True,
232
+ return_dict=True).hidden_states[self.select_layer]
233
+ vit_embeds = vit_embeds[:, 1:, :]
234
+
235
+ h = w = int(vit_embeds.shape[1] ** 0.5)
236
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
237
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
238
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
239
+ vit_embeds = self.mlp1(vit_embeds)
240
+ return vit_embeds
241
+
242
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
243
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
244
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
245
+ if history is not None or return_history:
246
+ print('Now multi-turn chat is not supported in batch_chat.')
247
+ raise NotImplementedError
248
+
249
+ if image_counts is not None:
250
+ num_patches_list = image_counts
251
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
252
+
253
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
254
+ self.img_context_token_id = img_context_token_id
255
+
256
+ if verbose and pixel_values is not None:
257
+ image_bs = pixel_values.shape[0]
258
+ print(f'dynamic ViT batch size: {image_bs}')
259
+
260
+ queries = []
261
+ for idx, num_patches in enumerate(num_patches_list):
262
+ question = questions[idx]
263
+ if pixel_values is not None and '<image>' not in question:
264
+ question = '<image>\n' + question
265
+ template = get_conv_template(self.template)
266
+ template.system_message = self.system_message
267
+ template.append_message(template.roles[0], question)
268
+ template.append_message(template.roles[1], None)
269
+ query = template.get_prompt()
270
+
271
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
272
+ query = query.replace('<image>', image_tokens, 1)
273
+ queries.append(query)
274
+
275
+ tokenizer.padding_side = 'left'
276
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
277
+ input_ids = model_inputs['input_ids'].to(self.device)
278
+ attention_mask = model_inputs['attention_mask'].to(self.device)
279
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
280
+ generation_config['eos_token_id'] = eos_token_id
281
+ generation_output = self.generate(
282
+ pixel_values=pixel_values,
283
+ input_ids=input_ids,
284
+ attention_mask=attention_mask,
285
+ **generation_config
286
+ )
287
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
288
+ responses = [response.split(template.sep)[0].strip() for response in responses]
289
+ return responses
290
+
291
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
292
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
293
+ verbose=False):
294
+
295
+ if history is None and pixel_values is not None and '<image>' not in question:
296
+ question = '<image>\n' + question
297
+
298
+ if num_patches_list is None:
299
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
300
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
301
+
302
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
303
+ self.img_context_token_id = img_context_token_id
304
+
305
+ template = get_conv_template(self.template)
306
+ template.system_message = self.system_message
307
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
308
+
309
+ history = [] if history is None else history
310
+ for (old_question, old_answer) in history:
311
+ template.append_message(template.roles[0], old_question)
312
+ template.append_message(template.roles[1], old_answer)
313
+ template.append_message(template.roles[0], question)
314
+ template.append_message(template.roles[1], None)
315
+ query = template.get_prompt()
316
+
317
+ if verbose and pixel_values is not None:
318
+ image_bs = pixel_values.shape[0]
319
+ print(f'dynamic ViT batch size: {image_bs}')
320
+
321
+ for num_patches in num_patches_list:
322
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
323
+ query = query.replace('<image>', image_tokens, 1)
324
+
325
+ model_inputs = tokenizer(query, return_tensors='pt')
326
+ input_ids = model_inputs['input_ids'].to(self.device)
327
+ attention_mask = model_inputs['attention_mask'].to(self.device)
328
+ generation_config['eos_token_id'] = eos_token_id
329
+ generation_output = self.generate(
330
+ pixel_values=pixel_values,
331
+ input_ids=input_ids,
332
+ attention_mask=attention_mask,
333
+ **generation_config
334
+ )
335
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
336
+ response = response.split(template.sep)[0].strip()
337
+ history.append((question, response))
338
+ if return_history:
339
+ return response, history
340
+ else:
341
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
342
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
343
+ if verbose:
344
+ print(query_to_print, response)
345
+ return response
346
+
347
+ @torch.no_grad()
348
+ def generate(
349
+ self,
350
+ pixel_values: Optional[torch.FloatTensor] = None,
351
+ input_ids: Optional[torch.FloatTensor] = None,
352
+ attention_mask: Optional[torch.LongTensor] = None,
353
+ visual_features: Optional[torch.FloatTensor] = None,
354
+ generation_config: Optional[GenerationConfig] = None,
355
+ output_hidden_states: Optional[bool] = None,
356
+ return_dict: Optional[bool] = None,
357
+ **generate_kwargs,
358
+ ) -> torch.LongTensor:
359
+
360
+ assert self.img_context_token_id is not None
361
+ if pixel_values is not None:
362
+ if visual_features is not None:
363
+ vit_embeds = visual_features
364
+ else:
365
+ vit_embeds = self.extract_feature(pixel_values)
366
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
367
+ B, N, C = input_embeds.shape
368
+ input_embeds = input_embeds.reshape(B * N, C)
369
+
370
+ input_ids = input_ids.reshape(B * N)
371
+ selected = (input_ids == self.img_context_token_id)
372
+ assert selected.sum() != 0
373
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
374
+
375
+ input_embeds = input_embeds.reshape(B, N, C)
376
+ else:
377
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
378
+
379
+ outputs = self.language_model.generate(
380
+ inputs_embeds=input_embeds,
381
+ attention_mask=attention_mask,
382
+ generation_config=generation_config,
383
+ output_hidden_states=output_hidden_states,
384
+ #return_dict=return_dict,
385
+ use_cache=True,
386
+ **generate_kwargs,
387
+ )
388
+
389
+ return outputs
390
+
391
+ @torch.no_grad()
392
+ def score(self, tokenizer, pixel_values, question, history=None, return_history=False,
393
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
394
+ verbose=False, score_key = "logits"):
395
+ """
396
+ Normal inference, 1x time required.
397
+ """
398
+ if self.special_tokens is None:
399
+ self.special_tokens = get_special_token(tokenizer)
400
+
401
+ if history is None and pixel_values is not None and '<image>' not in question:
402
+ question = '<image>\n' + question
403
+
404
+ if num_patches_list is None:
405
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
406
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
407
+
408
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
409
+ self.img_context_token_id = img_context_token_id
410
+
411
+ template = get_conv_template(self.template)
412
+ template.system_message = self.system_message
413
+
414
+ history = [] if history is None else history
415
+ for (old_question, old_answer) in history:
416
+ template.append_message(template.roles[0], old_question)
417
+ template.append_message(template.roles[1], old_answer)
418
+ template.append_message(template.roles[0], question)
419
+ template.append_message(template.roles[1], None)
420
+ query = template.get_prompt()
421
+
422
+ if verbose and pixel_values is not None:
423
+ image_bs = pixel_values.shape[0]
424
+ print(f'dynamic ViT batch size: {image_bs}')
425
+
426
+ for num_patches in num_patches_list:
427
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
428
+ query = query.replace('<image>', image_tokens, 1)
429
+
430
+ model_inputs = tokenizer(query, return_tensors='pt')
431
+ input_ids = model_inputs['input_ids'].to(self.device)
432
+ attention_mask = model_inputs['attention_mask'].to(self.device)
433
+
434
+ with torch.inference_mode():
435
+ generation_output = self.forward(
436
+ pixel_values=pixel_values,
437
+ input_ids=input_ids,
438
+ attention_mask=attention_mask,
439
+ image_flags=torch.ones((pixel_values.shape[0], 1)).bool()
440
+ )[score_key]
441
+
442
+ if score_key == 'logits':
443
+ return get_probs(generation_output[0,-1], self.special_tokens, way='softmax')
444
+ return generation_output[0,-1]
445
+
446
+ @torch.no_grad()
447
+ def run_metavoter(self, tokenizer, pixel_values, history=None, return_history=False,
448
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
449
+ verbose=False):
450
+ """
451
+ Slow inference, 2x time required.
452
+ """
453
+ question = '<image>\nRate the aesthetics of this human picture.'
454
+ question2 = '<image>\nRate the aesthetics of this human picture from 12 different dimensions.'
455
+
456
+ if self.special_tokens is None:
457
+ self.special_tokens = get_special_token(tokenizer)
458
+
459
+ if history is None and pixel_values is not None and '<image>' not in question:
460
+ question = '<image>\n' + question
461
+
462
+ if num_patches_list is None:
463
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
464
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
465
+
466
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
467
+ self.img_context_token_id = img_context_token_id
468
+
469
+ template = get_conv_template(self.template)
470
+ template.system_message = self.system_message
471
+
472
+ history = [] if history is None else history
473
+ for (old_question, old_answer) in history:
474
+ template.append_message(template.roles[0], old_question)
475
+ template.append_message(template.roles[1], old_answer)
476
+ template.append_message(template.roles[0], question)
477
+ template.append_message(template.roles[1], None)
478
+ query = template.get_prompt()
479
+
480
+ if verbose and pixel_values is not None:
481
+ image_bs = pixel_values.shape[0]
482
+ print(f'dynamic ViT batch size: {image_bs}')
483
+
484
+ for num_patches in num_patches_list:
485
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
486
+ query = query.replace('<image>', image_tokens, 1)
487
+
488
+ model_inputs = tokenizer(query, return_tensors='pt')
489
+ input_ids = model_inputs['input_ids'].to(self.device)
490
+ attention_mask = model_inputs['attention_mask'].to(self.device)
491
+
492
+ with torch.inference_mode():
493
+ generation_output = self.forward(
494
+ pixel_values=pixel_values,
495
+ input_ids=input_ids,
496
+ attention_mask=attention_mask,
497
+ image_flags=torch.ones((pixel_values.shape[0], 1)).bool()
498
+ )
499
+ logits = generation_output["logits"]
500
+ regression_score = generation_output['scores']
501
+ pred_score1, logits = float(regression_score[0,-1].cpu().detach()), logits[0,-1]
502
+ pred_score2 = get_probs(logits, self.special_tokens, way='softmax')
503
+ pred_score3 = float(self.score(tokenizer, pixel_values, question2, score_key = 'experts_scores').cpu().detach())
504
+ input_seq = [pred_score1, pred_score2, pred_score3]
505
+ input_tensor = torch.tensor(input_seq, dtype=self.language_model.dtype, device=self.language_model.device).unsqueeze(0) # (1, 2)
506
+ score = self.metavoter(input_tensor)
507
+ return float(score[0,0].cpu().detach())
508
+
509
+ @torch.no_grad()
510
+ def expert_annotataion(self, tokenizer, pixel_values, generation_config, history=None, return_history=False,
511
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
512
+ verbose=False):
513
+
514
+ question = '<image>\nRate the aesthetics of this human picture from 12 different dimensions.'
515
+ if history is None and pixel_values is not None and '<image>' not in question:
516
+ question = '<image>\n' + question
517
+
518
+ if num_patches_list is None:
519
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
520
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
521
+
522
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
523
+ self.img_context_token_id = img_context_token_id
524
+
525
+ template = get_conv_template(self.template)
526
+ template.system_message = self.system_message
527
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
528
+
529
+ history = [] if history is None else history
530
+ for (old_question, old_answer) in history:
531
+ template.append_message(template.roles[0], old_question)
532
+ template.append_message(template.roles[1], old_answer)
533
+ template.append_message(template.roles[0], question)
534
+ template.append_message(template.roles[1], None)
535
+ query = template.get_prompt()
536
+
537
+ if verbose and pixel_values is not None:
538
+ image_bs = pixel_values.shape[0]
539
+ print(f'dynamic ViT batch size: {image_bs}')
540
+
541
+ for num_patches in num_patches_list:
542
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
543
+ query = query.replace('<image>', image_tokens, 1)
544
+
545
+ model_inputs = tokenizer(query, return_tensors='pt')
546
+ input_ids = model_inputs['input_ids'].to(self.device)
547
+ attention_mask = model_inputs['attention_mask'].to(self.device)
548
+ generation_config['eos_token_id'] = eos_token_id
549
+ generation_output = self.generate(
550
+ pixel_values=pixel_values,
551
+ input_ids=input_ids,
552
+ attention_mask=attention_mask,
553
+ **generation_config
554
+ )
555
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
556
+ response = response.split(template.sep)[0].strip()
557
+ history.append((question, response))
558
+ if return_history:
559
+ return response, history
560
+ else:
561
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
562
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
563
+ if verbose:
564
+ print(query_to_print, response)
565
+ return response
566
+
567
+
568
+ @torch.no_grad()
569
+ def expert_score(self, tokenizer, pixel_values, history=None, return_history=False,
570
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
571
+ verbose=False):
572
+
573
+ question = '<image>\nRate the aesthetics of this human picture from 12 different dimensions.'
574
+
575
+ if self.special_tokens is None:
576
+ self.special_tokens = get_special_token(tokenizer)
577
+
578
+ if history is None and pixel_values is not None and '<image>' not in question:
579
+ question = '<image>\n' + question
580
+
581
+ if num_patches_list is None:
582
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
583
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
584
+
585
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
586
+ self.img_context_token_id = img_context_token_id
587
+
588
+ template = get_conv_template(self.template)
589
+ template.system_message = self.system_message
590
+
591
+ history = [] if history is None else history
592
+ for (old_question, old_answer) in history:
593
+ template.append_message(template.roles[0], old_question)
594
+ template.append_message(template.roles[1], old_answer)
595
+ template.append_message(template.roles[0], question)
596
+ template.append_message(template.roles[1], None)
597
+ query = template.get_prompt()
598
+
599
+ if verbose and pixel_values is not None:
600
+ image_bs = pixel_values.shape[0]
601
+ print(f'dynamic ViT batch size: {image_bs}')
602
+
603
+ for num_patches in num_patches_list:
604
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
605
+ query = query.replace('<image>', image_tokens, 1)
606
+
607
+ model_inputs = tokenizer(query, return_tensors='pt')
608
+ input_ids = model_inputs['input_ids'].to(self.device)
609
+ attention_mask = model_inputs['attention_mask'].to(self.device)
610
+
611
+ with torch.inference_mode():
612
+ generation_output = self.forward(
613
+ pixel_values=pixel_values,
614
+ input_ids=input_ids,
615
+ attention_mask=attention_mask,
616
+ image_flags=torch.ones((pixel_values.shape[0], 1)).bool()
617
+ )['experts_scores']
618
+
619
+ expert_scores = generation_output[0].cpu().detach()
620
+ names = ['Facial Brightness', 'Facial Feature Clarity', 'Facial Skin Tone', 'Facial Structure', 'Facial Contour Clarity', \
621
+ 'Facial Aesthetic Score', 'Outfit', 'Body Shape', 'Looks', 'Environment', 'General Appearance Aesthetic Score', \
622
+ 'Comprehensive Aesthetic Score']
623
+ return (expert_scores, {name:float(score) for (name, score) in zip(names, expert_scores)})
modeling_qwen.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.qwen2.modeling_qwen2 import *
2
+ from transformers.modeling_outputs import dataclass, ModelOutput
3
+ import torch.nn as nn
4
+ import torch.nn.init as init
5
+
6
+ @dataclass
7
+ class CausalLMOutputWithPastAndScore(ModelOutput):
8
+ """
9
+ Base class for causal language model (or autoregressive) outputs.
10
+
11
+ Args:
12
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
13
+ Language modeling loss (for next-token prediction).
14
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
15
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
16
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
17
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
18
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
19
+
20
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
21
+ `past_key_values` input) to speed up sequential decoding.
22
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
23
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
24
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
25
+
26
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
27
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
28
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
29
+ sequence_length)`.
30
+
31
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
32
+ heads.
33
+ """
34
+ loss: Optional[torch.FloatTensor] = None
35
+ logits: torch.FloatTensor = None
36
+ scores: torch.FloatTensor = None
37
+ experts_scores: torch.FloatTensor = None
38
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
39
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
40
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
41
+
42
+ def fixed_cross_entropy(source, target, num_items_in_batch: int = None, ignore_index: int = -100, **kwargs):
43
+ reduction = "sum" if num_items_in_batch is not None else "mean"
44
+ loss = nn.functional.cross_entropy(source, target, ignore_index=ignore_index, reduction=reduction)
45
+ if reduction == "sum":
46
+ loss = loss / num_items_in_batch
47
+ return loss
48
+
49
+
50
+ def ForCausalLMLoss(
51
+ logits, labels, vocab_size: int, num_items_in_batch: int = None, ignore_index: int = -100, **kwargs
52
+ ):
53
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
54
+ logits = logits.float()
55
+ # Shift so that tokens < n predict n
56
+ shift_logits = logits[..., :-1, :].contiguous()
57
+ shift_labels = labels[..., 1:].contiguous()
58
+
59
+ # Flatten the tokens
60
+ shift_logits = shift_logits.view(-1, vocab_size)
61
+ shift_labels = shift_labels.view(-1)
62
+ # Enable model parallelism
63
+ shift_labels = shift_labels.to(shift_logits.device)
64
+ loss = fixed_cross_entropy(shift_logits, shift_labels, num_items_in_batch, ignore_index, **kwargs)
65
+ return loss
66
+
67
+ def ForMseloss(logits, labels):
68
+ logits = logits.contiguous()
69
+ labels = labels.contiguous().to(device=logits.device,dtype=logits.dtype)
70
+ return nn.functional.mse_loss(logits, labels)
71
+
72
+ def ForMaeloss(logits, labels):
73
+ logits = logits.contiguous()
74
+ labels = labels.contiguous().to(device=logits.device,dtype=logits.dtype)
75
+ return nn.functional.l1_loss(logits, labels)
76
+
77
+ class Expert_Head(nn.Module):
78
+ def __init__(self, hidden_size):
79
+ super(Expert_Head, self).__init__()
80
+ self.expert_head1 = nn.Linear(hidden_size, 9)
81
+ self.linears = nn.ModuleList([nn.Linear(1,1) for _ in range(11)])
82
+ self.expert_head2 = nn.Sequential(nn.ReLU(),
83
+ nn.Linear(5, 1))
84
+ self.expert_head3 = nn.Sequential(nn.ReLU(),
85
+ nn.Linear(3, 1))
86
+ self.expert_head4 = nn.Sequential(nn.ReLU(),
87
+ nn.Linear(3, 1))
88
+
89
+ def forward(self, hidden_states, batch_size, sequence_lengths, is_expert):
90
+ scores2 = self.expert_head1(hidden_states)
91
+ pooled_scores2 = scores2[torch.arange(batch_size, device=scores2.device), sequence_lengths.to(device=scores2.device)]
92
+ for i in range(9):
93
+ pooled_scores2[:, i] = self.linears[i](pooled_scores2[:, i])
94
+
95
+ if is_expert is not None and is_expert[0] == 0:
96
+ with torch.no_grad():
97
+ pooled_scores3 = self.linears[9](self.expert_head2(pooled_scores2[:,:5]))
98
+ pooled_scores4 = self.linears[10](self.expert_head3(pooled_scores2[:,5:-1]))
99
+
100
+ expert_scores = self.expert_head4(torch.cat([pooled_scores3, pooled_scores4,pooled_scores2[:,-1].unsqueeze(1)], dim=1))
101
+
102
+ pooled_expert_scores = torch.cat([pooled_scores2[:,:5], pooled_scores3, pooled_scores2[:,5:], pooled_scores4, expert_scores], dim=1)
103
+ else:
104
+ pooled_scores3 = self.linears[9](self.expert_head2(pooled_scores2[:,:5]))
105
+ pooled_scores4 = self.linears[10](self.expert_head3(pooled_scores2[:,5:-1]))
106
+
107
+ expert_scores = self.expert_head4(torch.cat([pooled_scores3, pooled_scores4,pooled_scores2[:,-1].unsqueeze(1)], dim=1))
108
+
109
+ pooled_expert_scores = torch.cat([pooled_scores2[:,:5], pooled_scores3, pooled_scores2[:,5:], pooled_scores4, expert_scores], dim=1)
110
+
111
+ return pooled_expert_scores
112
+
113
+ class Qwen2ForCausalLM_score(Qwen2ForCausalLM):
114
+ _tied_weights_keys = ["lm_head.weight", "regression_head.weight"]
115
+
116
+ def __init__(self, config):
117
+ super().__init__(config)
118
+ self.lm_regression_head = nn.Linear(config.hidden_size, 1)
119
+ self.expert_head = Expert_Head(config.hidden_size)
120
+
121
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
122
+ @replace_return_docstrings(output_type=CausalLMOutputWithPastAndScore, config_class="Qwen2Config")
123
+ def forward(
124
+ self,
125
+ input_ids: torch.LongTensor = None,
126
+ attention_mask: Optional[torch.Tensor] = None,
127
+ position_ids: Optional[torch.LongTensor] = None,
128
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
129
+ inputs_embeds: Optional[torch.FloatTensor] = None,
130
+ labels: Optional[torch.LongTensor] = None,
131
+ use_cache: Optional[bool] = None,
132
+ output_attentions: Optional[bool] = None,
133
+ output_hidden_states: Optional[bool] = None,
134
+ return_dict: Optional[bool] = None,
135
+ cache_position: Optional[torch.LongTensor] = None,
136
+ num_logits_to_keep: int = 0,
137
+ scores_labels: Optional[torch.LongTensor] = None,
138
+ is_expert: Optional[torch.BoolTensor] = None,
139
+ **loss_kwargs,
140
+ ) -> Union[Tuple, CausalLMOutputWithPastAndScore]:
141
+ r"""
142
+ Args:
143
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
144
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
145
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
146
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
147
+
148
+ num_logits_to_keep (`int`, *optional*):
149
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
150
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
151
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
152
+
153
+ Returns:
154
+
155
+ Example:
156
+
157
+ ```python
158
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
159
+
160
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
161
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
162
+
163
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
164
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
165
+
166
+ >>> # Generate
167
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
168
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
169
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
170
+ ```"""
171
+
172
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
173
+ output_hidden_states = (
174
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
175
+ )
176
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
177
+
178
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
179
+ outputs = self.model(
180
+ input_ids=input_ids,
181
+ attention_mask=attention_mask,
182
+ position_ids=position_ids,
183
+ past_key_values=past_key_values,
184
+ inputs_embeds=inputs_embeds,
185
+ use_cache=use_cache,
186
+ output_attentions=output_attentions,
187
+ output_hidden_states=output_hidden_states,
188
+ return_dict=return_dict,
189
+ cache_position=cache_position,
190
+ )
191
+
192
+ hidden_states = outputs[0]
193
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
194
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
195
+
196
+ scores = self.lm_regression_head(hidden_states)
197
+
198
+ if input_ids is not None:
199
+ batch_size = input_ids.shape[0]
200
+ else:
201
+ batch_size = inputs_embeds.shape[0]
202
+
203
+ if self.config.pad_token_id is None and batch_size != 1:
204
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
205
+ if self.config.pad_token_id is None:
206
+ sequence_lengths = torch.tensor(-1, device=scores.device).int()
207
+ else:
208
+ if input_ids is not None:
209
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
210
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
211
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
212
+ sequence_lengths = sequence_lengths.to(scores.device)
213
+ else:
214
+ sequence_lengths = torch.tensor(-1, device=scores.device).int()
215
+ pooled_scores = scores[torch.arange(batch_size, device=scores.device), sequence_lengths]
216
+
217
+ pooled_expert_scores = self.expert_head(hidden_states, batch_size, sequence_lengths, is_expert)
218
+
219
+ loss = None
220
+ if labels is not None:
221
+ if scores_labels is not None and is_expert is not None and is_expert[0] == 0:
222
+ loss = ForCausalLMLoss(logits, labels, self.vocab_size, **loss_kwargs) + ForMseloss(pooled_scores, scores_labels[:,-1].unsqueeze(1))
223
+ elif scores_labels is not None and is_expert is not None and is_expert[0] == 1:
224
+ loss = ForCausalLMLoss(logits, labels, self.vocab_size, **loss_kwargs) + ForMseloss(pooled_expert_scores, scores_labels)
225
+ else:
226
+ loss = ForCausalLMLoss(logits, labels, self.vocab_size, **loss_kwargs)
227
+
228
+
229
+ if not return_dict:
230
+ output = (logits,) + outputs[1:]
231
+ return (loss,) + output if loss is not None else output
232
+
233
+ return CausalLMOutputWithPastAndScore(
234
+ loss=loss,
235
+ logits=logits,
236
+ scores=pooled_scores,
237
+ experts_scores=pooled_expert_scores,
238
+ past_key_values=outputs.past_key_values,
239
+ hidden_states=outputs.hidden_states,
240
+ attentions=outputs.attentions,
241
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 448,
3
+ "do_center_crop": true,
4
+ "do_normalize": true,
5
+ "do_resize": true,
6
+ "feature_extractor_type": "CLIPFeatureExtractor",
7
+ "image_mean": [
8
+ 0.485,
9
+ 0.456,
10
+ 0.406
11
+ ],
12
+ "image_std": [
13
+ 0.229,
14
+ 0.224,
15
+ 0.225
16
+ ],
17
+ "resample": 3,
18
+ "size": 448
19
+ }
sft_args.json ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "internvl2_1b_HumanAesExpert",
3
+ "model_id_or_path": "/home/zhengdezhi03/projects/Benchmark/models/HumanAesExpert-1B",
4
+ "model_revision": "main",
5
+ "full_determinism": false,
6
+ "sft_type": "full",
7
+ "freeze_parameters": [],
8
+ "freeze_vit": false,
9
+ "freeze_parameters_ratio": 0.0,
10
+ "additional_trainable_parameters": [
11
+ "language_model.lm_regression_head",
12
+ "language_model.expert_head.expert_head1"
13
+ ],
14
+ "tuner_backend": "peft",
15
+ "template_type": "internvl2_HumanAesExpert",
16
+ "output_dir": "/home/zhengdezhi03/for-open/HumanAesExpert/finetune-workspace/output/internvl2_1b_HumanAesExpert/v1-20250302-145030",
17
+ "add_output_dir_suffix": true,
18
+ "ddp_backend": "nccl",
19
+ "ddp_find_unused_parameters": null,
20
+ "ddp_broadcast_buffers": null,
21
+ "ddp_timeout": 1800,
22
+ "seed": 42,
23
+ "resume_from_checkpoint": null,
24
+ "resume_only_model": false,
25
+ "ignore_data_skip": false,
26
+ "dtype": "fp16",
27
+ "packing": false,
28
+ "train_backend": "transformers",
29
+ "tp": 1,
30
+ "pp": 1,
31
+ "min_lr": null,
32
+ "sequence_parallel": false,
33
+ "model_kwargs": {},
34
+ "loss_name": null,
35
+ "dataset": [
36
+ "/home/zhengdezhi03/projects/MakingData/Train_Dataset/all_public_image_paper_annotation.jsonl"
37
+ ],
38
+ "val_dataset": [],
39
+ "dataset_seed": 42,
40
+ "dataset_test_ratio": 0.01,
41
+ "use_loss_scale": false,
42
+ "loss_scale_config_path": "/home/zhengdezhi03/for-open/HumanAesExpert/swift/swift/llm/agent/default_loss_scale_config.json",
43
+ "system": null,
44
+ "tools_prompt": "react_en",
45
+ "max_length": 4096,
46
+ "truncation_strategy": "delete",
47
+ "check_dataset_strategy": "none",
48
+ "streaming": false,
49
+ "streaming_val_size": 0,
50
+ "streaming_buffer_size": 16384,
51
+ "model_name": [
52
+ null,
53
+ null
54
+ ],
55
+ "model_author": [
56
+ null,
57
+ null
58
+ ],
59
+ "quant_method": null,
60
+ "quantization_bit": 0,
61
+ "hqq_axis": 0,
62
+ "hqq_dynamic_config_path": null,
63
+ "bnb_4bit_comp_dtype": "fp16",
64
+ "bnb_4bit_quant_type": "nf4",
65
+ "bnb_4bit_use_double_quant": true,
66
+ "bnb_4bit_quant_storage": null,
67
+ "rescale_image": -1,
68
+ "target_modules": "^(language_model|mlp1)(?!.*(lm_head|output|emb|wte|shared|lm_regression_head|expert_head|expert_head1|expert_head2|expert_head3|expert_head4)).*",
69
+ "target_regex": null,
70
+ "modules_to_save": [],
71
+ "lora_rank": 8,
72
+ "lora_alpha": 32,
73
+ "lora_dropout": 0.05,
74
+ "lora_bias_trainable": "none",
75
+ "lora_dtype": null,
76
+ "lora_lr_ratio": null,
77
+ "use_rslora": false,
78
+ "use_dora": false,
79
+ "init_lora_weights": true,
80
+ "fourier_n_frequency": 2000,
81
+ "fourier_scaling": 300.0,
82
+ "rope_scaling": null,
83
+ "boft_block_size": 4,
84
+ "boft_block_num": 0,
85
+ "boft_n_butterfly_factor": 1,
86
+ "boft_dropout": 0.0,
87
+ "vera_rank": 256,
88
+ "vera_projection_prng_key": 0,
89
+ "vera_dropout": 0.0,
90
+ "vera_d_initial": 0.1,
91
+ "adapter_act": "gelu",
92
+ "adapter_length": 128,
93
+ "use_galore": false,
94
+ "galore_target_modules": null,
95
+ "galore_rank": 128,
96
+ "galore_update_proj_gap": 50,
97
+ "galore_scale": 1.0,
98
+ "galore_proj_type": "std",
99
+ "galore_optim_per_parameter": false,
100
+ "galore_with_embedding": false,
101
+ "galore_quantization": false,
102
+ "galore_proj_quant": false,
103
+ "galore_proj_bits": 4,
104
+ "galore_proj_group_size": 256,
105
+ "galore_cos_threshold": 0.4,
106
+ "galore_gamma_proj": 2,
107
+ "galore_queue_size": 5,
108
+ "adalora_target_r": 8,
109
+ "adalora_init_r": 12,
110
+ "adalora_tinit": 0,
111
+ "adalora_tfinal": 0,
112
+ "adalora_deltaT": 1,
113
+ "adalora_beta1": 0.85,
114
+ "adalora_beta2": 0.85,
115
+ "adalora_orth_reg_weight": 0.5,
116
+ "ia3_feedforward_modules": [],
117
+ "llamapro_num_new_blocks": 4,
118
+ "llamapro_num_groups": null,
119
+ "neftune_noise_alpha": null,
120
+ "neftune_backend": "transformers",
121
+ "lisa_activated_layers": 0,
122
+ "lisa_step_interval": 20,
123
+ "reft_layer_key": null,
124
+ "reft_layers": null,
125
+ "reft_rank": 4,
126
+ "reft_intervention_type": "LoreftIntervention",
127
+ "reft_args": null,
128
+ "use_liger": false,
129
+ "gradient_checkpointing": true,
130
+ "vit_use_gc": true,
131
+ "deepspeed": {
132
+ "fp16": {
133
+ "enabled": "auto",
134
+ "loss_scale": 0,
135
+ "loss_scale_window": 1000,
136
+ "initial_scale_power": 16,
137
+ "hysteresis": 2,
138
+ "min_loss_scale": 1
139
+ },
140
+ "bf16": {
141
+ "enabled": "auto"
142
+ },
143
+ "optimizer": {
144
+ "type": "AdamW",
145
+ "params": {
146
+ "lr": "auto",
147
+ "betas": "auto",
148
+ "eps": "auto",
149
+ "weight_decay": "auto"
150
+ }
151
+ },
152
+ "scheduler": {
153
+ "type": "WarmupCosineLR",
154
+ "params": {
155
+ "total_num_steps": "auto",
156
+ "warmup_num_steps": "auto"
157
+ }
158
+ },
159
+ "zero_optimization": {
160
+ "stage": 2,
161
+ "offload_optimizer": {
162
+ "device": "none",
163
+ "pin_memory": true
164
+ },
165
+ "allgather_partitions": true,
166
+ "allgather_bucket_size": 200000000.0,
167
+ "overlap_comm": true,
168
+ "reduce_scatter": true,
169
+ "reduce_bucket_size": 200000000.0,
170
+ "contiguous_gradients": true
171
+ },
172
+ "gradient_accumulation_steps": "auto",
173
+ "gradient_clipping": "auto",
174
+ "steps_per_print": 2000,
175
+ "train_batch_size": "auto",
176
+ "train_micro_batch_size_per_gpu": "auto",
177
+ "wall_clock_breakdown": false
178
+ },
179
+ "batch_size": 1,
180
+ "eval_batch_size": 1,
181
+ "auto_find_batch_size": false,
182
+ "num_train_epochs": 2,
183
+ "max_steps": -1,
184
+ "optim": "adamw_torch",
185
+ "adam_beta1": 0.9,
186
+ "adam_beta2": 0.95,
187
+ "adam_epsilon": 1e-08,
188
+ "learning_rate": 0.0001,
189
+ "weight_decay": 0.1,
190
+ "gradient_accumulation_steps": 4,
191
+ "max_grad_norm": 1,
192
+ "predict_with_generate": false,
193
+ "lr_scheduler_type": "cosine",
194
+ "lr_scheduler_kwargs": {},
195
+ "warmup_ratio": 0.05,
196
+ "warmup_steps": 0,
197
+ "eval_steps": 50,
198
+ "save_steps": 50,
199
+ "save_only_model": false,
200
+ "save_total_limit": 2,
201
+ "logging_steps": 5,
202
+ "acc_steps": 1,
203
+ "dataloader_num_workers": 1,
204
+ "dataloader_pin_memory": true,
205
+ "dataloader_drop_last": false,
206
+ "push_to_hub": false,
207
+ "hub_model_id": null,
208
+ "hub_token": null,
209
+ "hub_private_repo": false,
210
+ "hub_strategy": "every_save",
211
+ "test_oom_error": false,
212
+ "disable_tqdm": false,
213
+ "lazy_tokenize": true,
214
+ "preprocess_num_proc": 1,
215
+ "use_flash_attn": false,
216
+ "ignore_args_error": false,
217
+ "check_model_is_latest": true,
218
+ "logging_dir": "/home/zhengdezhi03/for-open/HumanAesExpert/finetune-workspace/output/internvl2_1b_HumanAesExpert/v1-20250302-145030/runs",
219
+ "report_to": [
220
+ "tensorboard"
221
+ ],
222
+ "acc_strategy": "token",
223
+ "save_on_each_node": false,
224
+ "evaluation_strategy": "steps",
225
+ "save_strategy": "steps",
226
+ "save_safetensors": true,
227
+ "gpu_memory_fraction": null,
228
+ "include_num_input_tokens_seen": false,
229
+ "local_repo_path": null,
230
+ "custom_register_path": "/home/zhengdezhi03/for-open/HumanAesExpert/finetune-workspace/HumanAesExpert_register6.py",
231
+ "custom_dataset_info": null,
232
+ "device_map_config": null,
233
+ "device_max_memory": [],
234
+ "max_new_tokens": 2048,
235
+ "do_sample": null,
236
+ "temperature": null,
237
+ "top_k": null,
238
+ "top_p": null,
239
+ "repetition_penalty": null,
240
+ "num_beams": 1,
241
+ "fsdp": "",
242
+ "fsdp_config": null,
243
+ "sequence_parallel_size": 1,
244
+ "model_layer_cls_name": null,
245
+ "metric_warmup_step": 0,
246
+ "fsdp_num": 1,
247
+ "per_device_train_batch_size": null,
248
+ "per_device_eval_batch_size": null,
249
+ "eval_strategy": null,
250
+ "self_cognition_sample": 0,
251
+ "train_dataset_mix_ratio": 0.0,
252
+ "train_dataset_mix_ds": [
253
+ "ms-bench"
254
+ ],
255
+ "train_dataset_sample": -1,
256
+ "val_dataset_sample": null,
257
+ "safe_serialization": null,
258
+ "only_save_model": null,
259
+ "neftune_alpha": null,
260
+ "deepspeed_config_path": null,
261
+ "model_cache_dir": null,
262
+ "lora_dropout_p": null,
263
+ "lora_target_modules": [],
264
+ "lora_target_regex": null,
265
+ "lora_modules_to_save": [],
266
+ "boft_target_modules": [],
267
+ "boft_modules_to_save": [],
268
+ "vera_target_modules": [],
269
+ "vera_modules_to_save": [],
270
+ "ia3_target_modules": [],
271
+ "ia3_modules_to_save": [],
272
+ "custom_train_dataset_path": [],
273
+ "custom_val_dataset_path": [],
274
+ "device_map_config_path": null,
275
+ "push_hub_strategy": null,
276
+ "use_self_cognition": false,
277
+ "is_multimodal": true,
278
+ "is_vision": true,
279
+ "lora_use_embedding": false,
280
+ "lora_use_all": false,
281
+ "lora_m2s_use_embedding": false,
282
+ "lora_m2s_use_ln": false,
283
+ "torch_dtype": "torch.float16",
284
+ "fp16": true,
285
+ "bf16": false,
286
+ "rank": 0,
287
+ "local_rank": 0,
288
+ "world_size": 4,
289
+ "local_world_size": 4,
290
+ "bnb_4bit_compute_dtype": "torch.float16",
291
+ "load_in_4bit": false,
292
+ "load_in_8bit": false,
293
+ "train_sampler_random": true,
294
+ "train_type": "sft",
295
+ "training_args": "Seq2SeqTrainingArguments(output_dir='/home/zhengdezhi03/for-open/HumanAesExpert/finetune-workspace/output/internvl2_1b_HumanAesExpert/v1-20250302-145030', overwrite_output_dir=False, do_train=False, do_eval=True, do_predict=False, eval_strategy=<IntervalStrategy.STEPS: 'steps'>, prediction_loss_only=False, per_device_train_batch_size=1, per_device_eval_batch_size=1, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=4, eval_accumulation_steps=None, eval_delay=0, torch_empty_cache_steps=None, learning_rate=0.0001, weight_decay=0.1, adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-08, max_grad_norm=1, num_train_epochs=2, max_steps=-1, lr_scheduler_type=<SchedulerType.COSINE: 'cosine'>, lr_scheduler_kwargs={}, warmup_ratio=0.05, warmup_steps=0, log_level='passive', log_level_replica='warning', log_on_each_node=True, logging_dir='/home/zhengdezhi03/for-open/HumanAesExpert/finetune-workspace/output/internvl2_1b_HumanAesExpert/v1-20250302-145030/runs', logging_strategy=<IntervalStrategy.STEPS: 'steps'>, logging_first_step=True, logging_steps=5, logging_nan_inf_filter=True, save_strategy=<IntervalStrategy.STEPS: 'steps'>, save_steps=50, save_total_limit=2, save_safetensors=True, save_on_each_node=False, save_only_model=False, restore_callback_states_from_checkpoint=False, no_cuda=False, use_cpu=False, use_mps_device=False, seed=42, data_seed=42, jit_mode_eval=False, use_ipex=False, bf16=False, fp16=True, fp16_opt_level='O1', half_precision_backend='auto', bf16_full_eval=False, fp16_full_eval=False, tf32=None, local_rank=0, ddp_backend='nccl', tpu_num_cores=None, tpu_metrics_debug=False, debug=[], dataloader_drop_last=False, eval_steps=50, dataloader_num_workers=1, dataloader_prefetch_factor=None, past_index=-1, run_name='/home/zhengdezhi03/for-open/HumanAesExpert/finetune-workspace/output/internvl2_1b_HumanAesExpert/v1-20250302-145030', disable_tqdm=False, remove_unused_columns=False, label_names=None, load_best_model_at_end=False, metric_for_best_model='loss', greater_is_better=False, ignore_data_skip=False, fsdp=[], fsdp_min_num_params=0, fsdp_config={'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}, fsdp_transformer_layer_cls_to_wrap=None, accelerator_config=AcceleratorConfig(split_batches=False, dispatch_batches=False, even_batches=True, use_seedable_sampler=True, non_blocking=False, gradient_accumulation_kwargs=None, use_configured_state=False), deepspeed={'fp16': {'enabled': 'auto', 'loss_scale': 0, 'loss_scale_window': 1000, 'initial_scale_power': 16, 'hysteresis': 2, 'min_loss_scale': 1}, 'bf16': {'enabled': 'auto'}, 'optimizer': {'type': 'AdamW', 'params': {'lr': 'auto', 'betas': 'auto', 'eps': 'auto', 'weight_decay': 'auto'}}, 'scheduler': {'type': 'WarmupCosineLR', 'params': {'total_num_steps': 'auto', 'warmup_num_steps': 'auto'}}, 'zero_optimization': {'stage': 2, 'offload_optimizer': {'device': 'none', 'pin_memory': True}, 'allgather_partitions': True, 'allgather_bucket_size': 200000000.0, 'overlap_comm': True, 'reduce_scatter': True, 'reduce_bucket_size': 200000000.0, 'contiguous_gradients': True}, 'gradient_accumulation_steps': 'auto', 'gradient_clipping': 'auto', 'steps_per_print': 2000, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'wall_clock_breakdown': False}, label_smoothing_factor=0.0, optim=<OptimizerNames.ADAMW_TORCH: 'adamw_torch'>, optim_args=None, adafactor=False, group_by_length=False, length_column_name='length', report_to=['tensorboard'], ddp_find_unused_parameters=False, ddp_bucket_cap_mb=None, ddp_broadcast_buffers=False, dataloader_pin_memory=True, dataloader_persistent_workers=False, skip_memory_metrics=True, use_legacy_prediction_loop=False, push_to_hub=False, resume_from_checkpoint=None, hub_model_id=None, hub_strategy=<HubStrategy.EVERY_SAVE: 'every_save'>, hub_token=None, hub_private_repo=False, hub_always_push=False, gradient_checkpointing=True, gradient_checkpointing_kwargs=None, include_inputs_for_metrics=False, eval_do_concat_batches=True, fp16_backend='auto', evaluation_strategy=None, push_to_hub_model_id=None, push_to_hub_organization=None, push_to_hub_token=None, mp_parameters='', auto_find_batch_size=False, full_determinism=False, torchdynamo=None, ray_scope='last', ddp_timeout=1800, torch_compile=False, torch_compile_backend=None, torch_compile_mode=None, dispatch_batches=None, split_batches=None, include_tokens_per_second=False, include_num_input_tokens_seen=False, neftune_noise_alpha=None, optim_target_modules=None, batch_eval_metrics=False, eval_on_start=False, eval_use_gather_object=False, sortish_sampler=False, predict_with_generate=False, generation_max_length=None, generation_num_beams=None, generation_config=GenerationConfig {\n \"eos_token_id\": 151645,\n \"max_new_tokens\": 2048,\n \"pad_token_id\": 151643\n}\n, acc_strategy='token', loss_name=None, additional_saved_files=[], train_sampler_random=True, metric_warmup_step=0, train_dataset_sample=-1)"
296
+ }
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_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