wzk1015 douwh commited on
Commit
0e1e0cf
1 Parent(s): 3c63f40

Upload 18 files (#5)

Browse files

- Upload 18 files (0e37d4eca76d5ba35f7cdc00fa818f627ed47261)


Co-authored-by: dou wenhan <[email protected]>

added_tokens.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 92552,
3
+ "</img>": 92545,
4
+ "</quad>": 92548,
5
+ "</ref>": 92550,
6
+ "<IMG_CONTEXT>": 92546,
7
+ "<box>": 92551,
8
+ "<img>": 92544,
9
+ "<quad>": 92547,
10
+ "<ref>": 92549
11
+ }
config.json ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "_name_or_path": "./work_dirs/internvl_chat_lite/internvl_chat_v1_5_internlm2_1_8b_dynamic12_res_alignment_pt_mlp_unfreeze_attn_5e-5/checkpoint-70000",
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
+ "llm_config": {
16
+ "_name_or_path": "./my_pretrained/internlm2-chat-1_8b_ve",
17
+ "add_cross_attention": false,
18
+ "architectures": [
19
+ "InternLM2VEForCausalLM"
20
+ ],
21
+ "attn_implementation": "flash_attention_2",
22
+ "auto_map": {
23
+ "AutoConfig": "configuration_internlm2_.InternLM2Config",
24
+ "AutoModel": "modeling_internlm2_ve.InternLM2VEForCausalLM",
25
+ "AutoModelForCausalLM": "modeling_internlm2_ve.InternLM2VEForCausalLM"
26
+ },
27
+ "bad_words_ids": null,
28
+ "begin_suppress_tokens": null,
29
+ "bias": false,
30
+ "bos_token_id": 1,
31
+ "chunk_size_feed_forward": 0,
32
+ "cross_attention_hidden_size": null,
33
+ "decoder_start_token_id": null,
34
+ "diversity_penalty": 0.0,
35
+ "do_sample": false,
36
+ "early_stopping": false,
37
+ "encoder_no_repeat_ngram_size": 0,
38
+ "eos_token_id": 2,
39
+ "expert_dp_comm": "none",
40
+ "exponential_decay_length_penalty": null,
41
+ "finetuning_task": null,
42
+ "forced_bos_token_id": null,
43
+ "forced_eos_token_id": null,
44
+ "hidden_act": "silu",
45
+ "hidden_size": 2048,
46
+ "id2label": {
47
+ "0": "LABEL_0",
48
+ "1": "LABEL_1"
49
+ },
50
+ "initializer_range": 0.02,
51
+ "intermediate_size": 8192,
52
+ "is_decoder": false,
53
+ "is_encoder_decoder": false,
54
+ "label2id": {
55
+ "LABEL_0": 0,
56
+ "LABEL_1": 1
57
+ },
58
+ "length_penalty": 1.0,
59
+ "max_length": 20,
60
+ "max_position_embeddings": 32768,
61
+ "min_length": 0,
62
+ "model_type": "internlm2",
63
+ "moe_top_k": 1,
64
+ "no_repeat_ngram_size": 0,
65
+ "num_attention_heads": 16,
66
+ "num_beam_groups": 1,
67
+ "num_beams": 1,
68
+ "num_expert": -1,
69
+ "num_hidden_layers": 24,
70
+ "num_key_value_heads": 8,
71
+ "num_return_sequences": 1,
72
+ "output_attentions": false,
73
+ "output_hidden_states": true,
74
+ "output_scores": false,
75
+ "pad_token_id": 2,
76
+ "prefix": null,
77
+ "problem_type": null,
78
+ "pruned_heads": {},
79
+ "remove_invalid_values": false,
80
+ "repetition_penalty": 1.0,
81
+ "return_dict": true,
82
+ "return_dict_in_generate": false,
83
+ "rms_norm_eps": 1e-05,
84
+ "rope_scaling": null,
85
+ "rope_theta": 1000000,
86
+ "sep_token_id": null,
87
+ "suppress_tokens": null,
88
+ "task_specific_params": null,
89
+ "temperature": 1.0,
90
+ "tf_legacy_loss": false,
91
+ "tie_encoder_decoder": false,
92
+ "tie_word_embeddings": false,
93
+ "tokenizer_class": null,
94
+ "top_k": 50,
95
+ "top_p": 1.0,
96
+ "torch_dtype": "bfloat16",
97
+ "torchscript": false,
98
+ "transformers_version": "4.37.2",
99
+ "typical_p": 1.0,
100
+ "use_bfloat16": false,
101
+ "use_cache": false,
102
+ "vocab_size": 92553
103
+ },
104
+ "max_dynamic_patch": 24,
105
+ "min_dynamic_patch": 1,
106
+ "model_type": "internvl_chat",
107
+ "pad2square": false,
108
+ "ps_version": "v2",
109
+ "select_layer": -1,
110
+ "template": "internlm2-chat",
111
+ "torch_dtype": "bfloat16",
112
+ "transformers_version": null,
113
+ "use_backbone_lora": 0,
114
+ "use_llm_lora": 0,
115
+ "use_thumbnail": true,
116
+ "vision_config": {
117
+ "architectures": [
118
+ "InternVisionPatchModel"
119
+ ],
120
+ "auto_map": {
121
+ "AutoConfig": "configuration_intern_patch.InternVisionPatchConfig",
122
+ "AutoModel": "modeling_intern_patch.InternVisionPatchModel"
123
+ },
124
+ "hidden_size": 1024,
125
+ "image_size": 448,
126
+ "model_type": "intern_vit_patch",
127
+ "patch_size": 14
128
+ }
129
+ }
configuration_intern_patch.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+
16
+ class InternVisionPatchConfig(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_patch'
63
+
64
+ def __init__(
65
+ self,
66
+ patch_size=14,
67
+ image_size=224,
68
+ hidden_size=3200,
69
+ **kwargs,
70
+ ):
71
+ super().__init__(**kwargs)
72
+
73
+ self.hidden_size = hidden_size
74
+ self.patch_size = patch_size
75
+ self.image_size = image_size
76
+
77
+ @classmethod
78
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
79
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
80
+
81
+ if 'vision_config' in config_dict:
82
+ config_dict = config_dict['vision_config']
83
+
84
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
85
+ logger.warning(
86
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
87
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
88
+ )
89
+
90
+
91
+ return cls.from_dict(config_dict, **kwargs)
configuration_internlm2.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ InternLM2 model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
24
+
25
+
26
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
27
+ class InternLM2Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
30
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`InternLM2Model`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ Example:
72
+
73
+ """
74
+ model_type = 'internlm2'
75
+ _auto_class = 'AutoConfig'
76
+
77
+ def __init__( # pylint: disable=W0102
78
+ self,
79
+ vocab_size=103168,
80
+ hidden_size=4096,
81
+ intermediate_size=11008,
82
+ num_hidden_layers=32,
83
+ num_attention_heads=32,
84
+ num_key_value_heads=None,
85
+ hidden_act='silu',
86
+ max_position_embeddings=2048,
87
+ initializer_range=0.02,
88
+ rms_norm_eps=1e-6,
89
+ use_cache=True,
90
+ pad_token_id=0,
91
+ bos_token_id=1,
92
+ eos_token_id=2,
93
+ tie_word_embeddings=False,
94
+ bias=True,
95
+ rope_theta=10000,
96
+ rope_scaling=None,
97
+ attn_implementation='eager',
98
+ **kwargs,
99
+ ):
100
+ self.vocab_size = vocab_size
101
+ self.max_position_embeddings = max_position_embeddings
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.bias = bias
107
+
108
+ if num_key_value_heads is None:
109
+ num_key_value_heads = num_attention_heads
110
+ self.num_key_value_heads = num_key_value_heads
111
+
112
+ self.hidden_act = hidden_act
113
+ self.initializer_range = initializer_range
114
+ self.rms_norm_eps = rms_norm_eps
115
+ self.use_cache = use_cache
116
+ self.rope_theta = rope_theta
117
+ self.rope_scaling = rope_scaling
118
+ self._rope_scaling_validation()
119
+
120
+ self.attn_implementation = attn_implementation
121
+ if self.attn_implementation is None:
122
+ self.attn_implementation = 'eager'
123
+ super().__init__(
124
+ pad_token_id=pad_token_id,
125
+ bos_token_id=bos_token_id,
126
+ eos_token_id=eos_token_id,
127
+ tie_word_embeddings=tie_word_embeddings,
128
+ **kwargs,
129
+ )
130
+
131
+ def _rope_scaling_validation(self):
132
+ """
133
+ Validate the `rope_scaling` configuration.
134
+ """
135
+ if self.rope_scaling is None:
136
+ return
137
+
138
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
139
+ raise ValueError(
140
+ '`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
141
+ f'got {self.rope_scaling}'
142
+ )
143
+ rope_scaling_type = self.rope_scaling.get('type', None)
144
+ rope_scaling_factor = self.rope_scaling.get('factor', None)
145
+ if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
146
+ raise ValueError(
147
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
148
+ )
149
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
150
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
configuration_internvl_chat.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .configuration_internlm2 import InternLM2Config
10
+ from transformers import AutoConfig, LlamaConfig, Qwen2Config
11
+ from transformers.configuration_utils import PretrainedConfig
12
+ from transformers.utils import logging
13
+
14
+ from .configuration_intern_patch import InternVisionPatchConfig
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+
19
+ class InternVLChatConfig(PretrainedConfig):
20
+ model_type = 'internvl_chat'
21
+ is_composition = True
22
+
23
+ def __init__(
24
+ self,
25
+ vision_config=None,
26
+ llm_config=None,
27
+ use_backbone_lora=0,
28
+ use_llm_lora=0,
29
+ pad2square=False,
30
+ select_layer=-1,
31
+ force_image_size=None,
32
+ downsample_ratio=0.5,
33
+ template=None,
34
+ dynamic_image_size=False,
35
+ use_thumbnail=False,
36
+ ps_version='v1',
37
+ min_dynamic_patch=1,
38
+ max_dynamic_patch=6,
39
+ **kwargs):
40
+ super().__init__(**kwargs)
41
+
42
+ if vision_config is None:
43
+ vision_config = {}
44
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
45
+
46
+ if llm_config is None:
47
+ llm_config = {}
48
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
49
+
50
+ if vision_config and vision_config['model_type']=='intern_vit_patch':
51
+ self.vision_config = InternVisionPatchConfig(**vision_config)
52
+ else:
53
+ raise ValueError('Unsupported vision model type: {}'.format(vision_config['model_type']))
54
+ if llm_config['architectures'][0] == 'LlamaForCausalLM':
55
+ self.llm_config = LlamaConfig(**llm_config)
56
+ elif llm_config['architectures'][0] == 'InternLM2ForCausalLM':
57
+ self.llm_config = InternLM2Config(**llm_config)
58
+ elif llm_config['architectures'][0] == 'InternLM2VEForCausalLM':
59
+ self.llm_config = InternLM2Config(**llm_config)
60
+ elif llm_config['architectures'][0] == 'Qwen2ForCausalLM':
61
+ self.llm_config = Qwen2Config(**llm_config)
62
+ else:
63
+ raise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))
64
+ self.use_backbone_lora = use_backbone_lora
65
+ self.use_llm_lora = use_llm_lora
66
+ self.pad2square = pad2square
67
+ self.select_layer = select_layer
68
+ self.force_image_size = force_image_size
69
+ self.downsample_ratio = downsample_ratio
70
+ self.template = template
71
+ self.dynamic_image_size = dynamic_image_size
72
+ self.use_thumbnail = use_thumbnail
73
+ self.ps_version = ps_version # pixel shuffle version
74
+ self.min_dynamic_patch = min_dynamic_patch
75
+ self.max_dynamic_patch = max_dynamic_patch
76
+
77
+ logger.info(f'vision_select_layer: {self.select_layer}')
78
+ logger.info(f'ps_version: {self.ps_version}')
79
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
80
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
81
+
82
+ def to_dict(self):
83
+ """
84
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
85
+
86
+ Returns:
87
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
88
+ """
89
+ output = copy.deepcopy(self.__dict__)
90
+ output['vision_config'] = self.vision_config.to_dict()
91
+ output['llm_config'] = self.llm_config.to_dict()
92
+ output['model_type'] = self.__class__.model_type
93
+ output['use_backbone_lora'] = self.use_backbone_lora
94
+ output['use_llm_lora'] = self.use_llm_lora
95
+ output['pad2square'] = self.pad2square
96
+ output['select_layer'] = self.select_layer
97
+ output['force_image_size'] = self.force_image_size
98
+ output['downsample_ratio'] = self.downsample_ratio
99
+ output['template'] = self.template
100
+ output['dynamic_image_size'] = self.dynamic_image_size
101
+ output['use_thumbnail'] = self.use_thumbnail
102
+ output['ps_version'] = self.ps_version
103
+ output['min_dynamic_patch'] = self.min_dynamic_patch
104
+ output['max_dynamic_patch'] = self.max_dynamic_patch
105
+
106
+ return output
conversation.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+ """
7
+
8
+ import dataclasses
9
+ from enum import IntEnum, auto
10
+ from typing import Any, Dict, List, Tuple, Union
11
+
12
+
13
+ class SeparatorStyle(IntEnum):
14
+ """Separator styles."""
15
+
16
+ ADD_COLON_SINGLE = auto()
17
+ ADD_COLON_TWO = auto()
18
+ ADD_COLON_SPACE_SINGLE = auto()
19
+ NO_COLON_SINGLE = auto()
20
+ NO_COLON_TWO = auto()
21
+ ADD_NEW_LINE_SINGLE = auto()
22
+ LLAMA2 = auto()
23
+ CHATGLM = auto()
24
+ CHATML = auto()
25
+ CHATINTERN = auto()
26
+ DOLLY = auto()
27
+ RWKV = auto()
28
+ PHOENIX = auto()
29
+ ROBIN = auto()
30
+ FALCON_CHAT = auto()
31
+ CHATGLM3 = auto()
32
+ INTERNVL_ZH = auto()
33
+ MPT = auto()
34
+
35
+
36
+ @dataclasses.dataclass
37
+ class Conversation:
38
+ """A class that manages prompt templates and keeps all conversation history."""
39
+
40
+ # The name of this template
41
+ name: str
42
+ # The template of the system prompt
43
+ system_template: str = '{system_message}'
44
+ # The system message
45
+ system_message: str = ''
46
+ # The names of two roles
47
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
48
+ # All messages. Each item is (role, message).
49
+ messages: List[List[str]] = ()
50
+ # The number of few shot examples
51
+ offset: int = 0
52
+ # The separator style and configurations
53
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
54
+ sep: str = '\n'
55
+ sep2: str = None
56
+ # Stop criteria (the default one is EOS token)
57
+ stop_str: Union[str, List[str]] = None
58
+ # Stops generation if meeting any token in this list
59
+ stop_token_ids: List[int] = None
60
+
61
+ def get_prompt(self) -> str:
62
+ """Get the prompt for generation."""
63
+ system_prompt = self.system_template.format(system_message=self.system_message)
64
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
65
+ ret = system_prompt + self.sep
66
+ for role, message in self.messages:
67
+ if message:
68
+ ret += role + ': ' + message + self.sep
69
+ else:
70
+ ret += role + ':'
71
+ return ret
72
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
73
+ seps = [self.sep, self.sep2]
74
+ ret = system_prompt + seps[0]
75
+ for i, (role, message) in enumerate(self.messages):
76
+ if message:
77
+ ret += role + ': ' + message + seps[i % 2]
78
+ else:
79
+ ret += role + ':'
80
+ return ret
81
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
82
+ ret = system_prompt + self.sep
83
+ for role, message in self.messages:
84
+ if message:
85
+ ret += role + ': ' + message + self.sep
86
+ else:
87
+ ret += role + ': ' # must be end with a space
88
+ return ret
89
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
90
+ ret = '' if system_prompt == '' else system_prompt + self.sep
91
+ for role, message in self.messages:
92
+ if message:
93
+ ret += role + '\n' + message + self.sep
94
+ else:
95
+ ret += role + '\n'
96
+ return ret
97
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
98
+ ret = system_prompt
99
+ for role, message in self.messages:
100
+ if message:
101
+ ret += role + message + self.sep
102
+ else:
103
+ ret += role
104
+ return ret
105
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
106
+ seps = [self.sep, self.sep2]
107
+ ret = system_prompt
108
+ for i, (role, message) in enumerate(self.messages):
109
+ if message:
110
+ ret += role + message + seps[i % 2]
111
+ else:
112
+ ret += role
113
+ return ret
114
+ elif self.sep_style == SeparatorStyle.RWKV:
115
+ ret = system_prompt
116
+ for i, (role, message) in enumerate(self.messages):
117
+ if message:
118
+ ret += (
119
+ role
120
+ + ': '
121
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
122
+ )
123
+ ret += '\n\n'
124
+ else:
125
+ ret += role + ':'
126
+ return ret
127
+ elif self.sep_style == SeparatorStyle.LLAMA2:
128
+ seps = [self.sep, self.sep2]
129
+ if self.system_message:
130
+ ret = system_prompt
131
+ else:
132
+ ret = '[INST] '
133
+ for i, (role, message) in enumerate(self.messages):
134
+ tag = self.roles[i % 2]
135
+ if message:
136
+ if i == 0:
137
+ ret += message + ' '
138
+ else:
139
+ ret += tag + ' ' + message + seps[i % 2]
140
+ else:
141
+ ret += tag
142
+ return ret
143
+ elif self.sep_style == SeparatorStyle.CHATGLM:
144
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
145
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
146
+ round_add_n = 1 if self.name == 'chatglm2' else 0
147
+ if system_prompt:
148
+ ret = system_prompt + self.sep
149
+ else:
150
+ ret = ''
151
+
152
+ for i, (role, message) in enumerate(self.messages):
153
+ if i % 2 == 0:
154
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
155
+
156
+ if message:
157
+ ret += f'{role}:{message}{self.sep}'
158
+ else:
159
+ ret += f'{role}:'
160
+ return ret
161
+ elif self.sep_style == SeparatorStyle.CHATML:
162
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
163
+ for role, message in self.messages:
164
+ if message:
165
+ ret += role + '\n' + message + self.sep + '\n'
166
+ else:
167
+ ret += role + '\n'
168
+ return ret
169
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
170
+ ret = ''
171
+ if self.system_message:
172
+ ret += system_prompt
173
+ for role, message in self.messages:
174
+ if message:
175
+ ret += role + '\n' + ' ' + message
176
+ else:
177
+ ret += role
178
+ return ret
179
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
180
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
181
+ seps = [self.sep, self.sep2]
182
+ ret = system_prompt
183
+ for i, (role, message) in enumerate(self.messages):
184
+ # if i % 2 == 0:
185
+ # ret += "<s>"
186
+ if message:
187
+ ret += role + ':' + message + seps[i % 2] + '\n'
188
+ else:
189
+ ret += role + ':'
190
+ return ret
191
+ elif self.sep_style == SeparatorStyle.DOLLY:
192
+ seps = [self.sep, self.sep2]
193
+ ret = system_prompt
194
+ for i, (role, message) in enumerate(self.messages):
195
+ if message:
196
+ ret += role + ':\n' + message + seps[i % 2]
197
+ if i % 2 == 1:
198
+ ret += '\n\n'
199
+ else:
200
+ ret += role + ':\n'
201
+ return ret
202
+ elif self.sep_style == SeparatorStyle.PHOENIX:
203
+ ret = system_prompt
204
+ for role, message in self.messages:
205
+ if message:
206
+ ret += role + ': ' + '<s>' + message + '</s>'
207
+ else:
208
+ ret += role + ': ' + '<s>'
209
+ return ret
210
+ elif self.sep_style == SeparatorStyle.ROBIN:
211
+ ret = system_prompt + self.sep
212
+ for role, message in self.messages:
213
+ if message:
214
+ ret += role + ':\n' + message + self.sep
215
+ else:
216
+ ret += role + ':\n'
217
+ return ret
218
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
219
+ ret = ''
220
+ if self.system_message:
221
+ ret += system_prompt + self.sep
222
+ for role, message in self.messages:
223
+ if message:
224
+ ret += role + ': ' + message + self.sep
225
+ else:
226
+ ret += role + ':'
227
+
228
+ return ret
229
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
230
+ seps = [self.sep2, self.sep]
231
+ ret = self.system_message + seps[0]
232
+ for i, (role, message) in enumerate(self.messages):
233
+ if message:
234
+ ret += role + ': ' + message + seps[i % 2]
235
+ else:
236
+ ret += role + ':'
237
+ return ret
238
+ elif self.sep_style == SeparatorStyle.MPT:
239
+ ret = system_prompt + self.sep
240
+ for role, message in self.messages:
241
+ if message:
242
+ if type(message) is tuple:
243
+ message, _, _ = message
244
+ ret += role + message + self.sep
245
+ else:
246
+ ret += role
247
+ return ret
248
+ else:
249
+ raise ValueError(f'Invalid style: {self.sep_style}')
250
+
251
+ def set_system_message(self, system_message: str):
252
+ """Set the system message."""
253
+ self.system_message = system_message
254
+
255
+ def append_message(self, role: str, message: str):
256
+ """Append a new message."""
257
+ self.messages.append([role, message])
258
+
259
+ def update_last_message(self, message: str):
260
+ """Update the last output.
261
+
262
+ The last message is typically set to be None when constructing the prompt,
263
+ so we need to update it in-place after getting the response from a model.
264
+ """
265
+ self.messages[-1][1] = message
266
+
267
+ def to_gradio_chatbot(self):
268
+ """Convert the conversation to gradio chatbot format."""
269
+ ret = []
270
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
271
+ if i % 2 == 0:
272
+ ret.append([msg, None])
273
+ else:
274
+ ret[-1][-1] = msg
275
+ return ret
276
+
277
+ def to_openai_api_messages(self):
278
+ """Convert the conversation to OpenAI chat completion format."""
279
+ ret = [{'role': 'system', 'content': self.system_message}]
280
+
281
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
282
+ if i % 2 == 0:
283
+ ret.append({'role': 'user', 'content': msg})
284
+ else:
285
+ if msg is not None:
286
+ ret.append({'role': 'assistant', 'content': msg})
287
+ return ret
288
+
289
+ def copy(self):
290
+ return Conversation(
291
+ name=self.name,
292
+ system_template=self.system_template,
293
+ system_message=self.system_message,
294
+ roles=self.roles,
295
+ messages=[[x, y] for x, y in self.messages],
296
+ offset=self.offset,
297
+ sep_style=self.sep_style,
298
+ sep=self.sep,
299
+ sep2=self.sep2,
300
+ stop_str=self.stop_str,
301
+ stop_token_ids=self.stop_token_ids,
302
+ )
303
+
304
+ def dict(self):
305
+ return {
306
+ 'template_name': self.name,
307
+ 'system_message': self.system_message,
308
+ 'roles': self.roles,
309
+ 'messages': self.messages,
310
+ 'offset': self.offset,
311
+ }
312
+
313
+
314
+ # A global registry for all conversation templates
315
+ conv_templates: Dict[str, Conversation] = {}
316
+
317
+
318
+ def register_conv_template(template: Conversation, override: bool = False):
319
+ """Register a new conversation template."""
320
+ if not override:
321
+ assert (
322
+ template.name not in conv_templates
323
+ ), f'{template.name} has been registered.'
324
+
325
+ conv_templates[template.name] = template
326
+
327
+
328
+ def get_conv_template(name: str) -> Conversation:
329
+ """Get a conversation template."""
330
+ return conv_templates[name].copy()
331
+
332
+
333
+ # InternVL-Chat-V1-1 template
334
+ register_conv_template(
335
+ Conversation(
336
+ name='internvl_zh',
337
+ system_template='',
338
+ roles=('<human>', '<bot>'),
339
+ sep_style=SeparatorStyle.INTERNVL_ZH,
340
+ sep='</s>',
341
+ sep2=' ',
342
+ )
343
+ )
344
+
345
+
346
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
347
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
348
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
349
+ # Therefore, they are completely equivalent during inference.
350
+ register_conv_template(
351
+ Conversation(
352
+ name='Hermes-2',
353
+ system_template='<|im_start|>system\n{system_message}',
354
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
355
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态大语言模型。',
356
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
357
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
358
+ sep_style=SeparatorStyle.MPT,
359
+ sep='<|im_end|>',
360
+ stop_token_ids=[
361
+ 2,
362
+ 6,
363
+ 7,
364
+ 8,
365
+ ],
366
+ stop_str='<|endoftext|>',
367
+ )
368
+ )
369
+
370
+
371
+ register_conv_template(
372
+ Conversation(
373
+ name='internlm2-chat',
374
+ system_template='<|im_start|>system\n{system_message}',
375
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
376
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态大语言模型。',
377
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
378
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
379
+ sep_style=SeparatorStyle.MPT,
380
+ sep='<|im_end|>',
381
+ stop_token_ids=[
382
+ 2,
383
+ 92543,
384
+ 92542
385
+ ]
386
+ )
387
+ )
388
+
389
+
390
+ register_conv_template(
391
+ Conversation(
392
+ name='phi3-chat',
393
+ system_template='<|system|>\n{system_message}',
394
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
395
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态大语言模型。',
396
+ system_message='你是由上海人工智能实验室联合商汤科技开���的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
397
+ roles=('<|user|>\n', '<|assistant|>\n'),
398
+ sep_style=SeparatorStyle.MPT,
399
+ sep='<|end|>',
400
+ stop_token_ids=[
401
+ 2,
402
+ 32000,
403
+ 32007
404
+ ]
405
+ )
406
+ )
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.37.2"
4
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2b02da4f47d52a85237236e27465b6cbf2d1e5ab353e48b675940f680c5451b
3
+ size 4971164000
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4b37a238a9ef5a35ca20563c169101fbf764c8918439b9d6f7745831b19ac8c
3
+ size 1251579280
model.safetensors.index.json ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 6222710784
4
+ },
5
+ "weight_map": {
6
+ "language_model.model.layers.0.attention.wo.weight": "model-00001-of-00002.safetensors",
7
+ "language_model.model.layers.0.attention.wqkv.weight": "model-00001-of-00002.safetensors",
8
+ "language_model.model.layers.0.attention_norm.weight": "model-00001-of-00002.safetensors",
9
+ "language_model.model.layers.0.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
10
+ "language_model.model.layers.0.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
11
+ "language_model.model.layers.0.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
12
+ "language_model.model.layers.0.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
13
+ "language_model.model.layers.0.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
14
+ "language_model.model.layers.0.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
15
+ "language_model.model.layers.0.ffn_norm.weight": "model-00001-of-00002.safetensors",
16
+ "language_model.model.layers.1.attention.wo.weight": "model-00001-of-00002.safetensors",
17
+ "language_model.model.layers.1.attention.wqkv.weight": "model-00001-of-00002.safetensors",
18
+ "language_model.model.layers.1.attention_norm.weight": "model-00001-of-00002.safetensors",
19
+ "language_model.model.layers.1.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
20
+ "language_model.model.layers.1.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
21
+ "language_model.model.layers.1.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
22
+ "language_model.model.layers.1.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
23
+ "language_model.model.layers.1.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
24
+ "language_model.model.layers.1.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
25
+ "language_model.model.layers.1.ffn_norm.weight": "model-00001-of-00002.safetensors",
26
+ "language_model.model.layers.10.attention.wo.weight": "model-00001-of-00002.safetensors",
27
+ "language_model.model.layers.10.attention.wqkv.weight": "model-00001-of-00002.safetensors",
28
+ "language_model.model.layers.10.attention_norm.weight": "model-00001-of-00002.safetensors",
29
+ "language_model.model.layers.10.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
30
+ "language_model.model.layers.10.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
31
+ "language_model.model.layers.10.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
32
+ "language_model.model.layers.10.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
33
+ "language_model.model.layers.10.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
34
+ "language_model.model.layers.10.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
35
+ "language_model.model.layers.10.ffn_norm.weight": "model-00001-of-00002.safetensors",
36
+ "language_model.model.layers.11.attention.wo.weight": "model-00001-of-00002.safetensors",
37
+ "language_model.model.layers.11.attention.wqkv.weight": "model-00001-of-00002.safetensors",
38
+ "language_model.model.layers.11.attention_norm.weight": "model-00001-of-00002.safetensors",
39
+ "language_model.model.layers.11.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
40
+ "language_model.model.layers.11.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
41
+ "language_model.model.layers.11.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
42
+ "language_model.model.layers.11.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
43
+ "language_model.model.layers.11.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
44
+ "language_model.model.layers.11.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
45
+ "language_model.model.layers.11.ffn_norm.weight": "model-00001-of-00002.safetensors",
46
+ "language_model.model.layers.12.attention.wo.weight": "model-00001-of-00002.safetensors",
47
+ "language_model.model.layers.12.attention.wqkv.weight": "model-00001-of-00002.safetensors",
48
+ "language_model.model.layers.12.attention_norm.weight": "model-00001-of-00002.safetensors",
49
+ "language_model.model.layers.12.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
50
+ "language_model.model.layers.12.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
51
+ "language_model.model.layers.12.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
52
+ "language_model.model.layers.12.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
53
+ "language_model.model.layers.12.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
54
+ "language_model.model.layers.12.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
55
+ "language_model.model.layers.12.ffn_norm.weight": "model-00001-of-00002.safetensors",
56
+ "language_model.model.layers.13.attention.wo.weight": "model-00001-of-00002.safetensors",
57
+ "language_model.model.layers.13.attention.wqkv.weight": "model-00001-of-00002.safetensors",
58
+ "language_model.model.layers.13.attention_norm.weight": "model-00001-of-00002.safetensors",
59
+ "language_model.model.layers.13.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
60
+ "language_model.model.layers.13.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
61
+ "language_model.model.layers.13.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
62
+ "language_model.model.layers.13.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
63
+ "language_model.model.layers.13.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
64
+ "language_model.model.layers.13.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
65
+ "language_model.model.layers.13.ffn_norm.weight": "model-00001-of-00002.safetensors",
66
+ "language_model.model.layers.14.attention.wo.weight": "model-00001-of-00002.safetensors",
67
+ "language_model.model.layers.14.attention.wqkv.weight": "model-00001-of-00002.safetensors",
68
+ "language_model.model.layers.14.attention_norm.weight": "model-00001-of-00002.safetensors",
69
+ "language_model.model.layers.14.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
70
+ "language_model.model.layers.14.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
71
+ "language_model.model.layers.14.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
72
+ "language_model.model.layers.14.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
73
+ "language_model.model.layers.14.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
74
+ "language_model.model.layers.14.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
75
+ "language_model.model.layers.14.ffn_norm.weight": "model-00001-of-00002.safetensors",
76
+ "language_model.model.layers.15.attention.wo.weight": "model-00001-of-00002.safetensors",
77
+ "language_model.model.layers.15.attention.wqkv.weight": "model-00001-of-00002.safetensors",
78
+ "language_model.model.layers.15.attention_norm.weight": "model-00001-of-00002.safetensors",
79
+ "language_model.model.layers.15.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
80
+ "language_model.model.layers.15.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
81
+ "language_model.model.layers.15.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
82
+ "language_model.model.layers.15.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
83
+ "language_model.model.layers.15.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
84
+ "language_model.model.layers.15.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
85
+ "language_model.model.layers.15.ffn_norm.weight": "model-00001-of-00002.safetensors",
86
+ "language_model.model.layers.16.attention.wo.weight": "model-00001-of-00002.safetensors",
87
+ "language_model.model.layers.16.attention.wqkv.weight": "model-00001-of-00002.safetensors",
88
+ "language_model.model.layers.16.attention_norm.weight": "model-00001-of-00002.safetensors",
89
+ "language_model.model.layers.16.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
90
+ "language_model.model.layers.16.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
91
+ "language_model.model.layers.16.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
92
+ "language_model.model.layers.16.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
93
+ "language_model.model.layers.16.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
94
+ "language_model.model.layers.16.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
95
+ "language_model.model.layers.16.ffn_norm.weight": "model-00001-of-00002.safetensors",
96
+ "language_model.model.layers.17.attention.wo.weight": "model-00001-of-00002.safetensors",
97
+ "language_model.model.layers.17.attention.wqkv.weight": "model-00001-of-00002.safetensors",
98
+ "language_model.model.layers.17.attention_norm.weight": "model-00001-of-00002.safetensors",
99
+ "language_model.model.layers.17.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
100
+ "language_model.model.layers.17.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
101
+ "language_model.model.layers.17.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
102
+ "language_model.model.layers.17.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
103
+ "language_model.model.layers.17.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
104
+ "language_model.model.layers.17.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
105
+ "language_model.model.layers.17.ffn_norm.weight": "model-00001-of-00002.safetensors",
106
+ "language_model.model.layers.18.attention.wo.weight": "model-00001-of-00002.safetensors",
107
+ "language_model.model.layers.18.attention.wqkv.weight": "model-00001-of-00002.safetensors",
108
+ "language_model.model.layers.18.attention_norm.weight": "model-00001-of-00002.safetensors",
109
+ "language_model.model.layers.18.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
110
+ "language_model.model.layers.18.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
111
+ "language_model.model.layers.18.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
112
+ "language_model.model.layers.18.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
113
+ "language_model.model.layers.18.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
114
+ "language_model.model.layers.18.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
115
+ "language_model.model.layers.18.ffn_norm.weight": "model-00001-of-00002.safetensors",
116
+ "language_model.model.layers.19.attention.wo.weight": "model-00001-of-00002.safetensors",
117
+ "language_model.model.layers.19.attention.wqkv.weight": "model-00001-of-00002.safetensors",
118
+ "language_model.model.layers.19.attention_norm.weight": "model-00001-of-00002.safetensors",
119
+ "language_model.model.layers.19.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
120
+ "language_model.model.layers.19.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
121
+ "language_model.model.layers.19.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
122
+ "language_model.model.layers.19.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
123
+ "language_model.model.layers.19.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
124
+ "language_model.model.layers.19.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
125
+ "language_model.model.layers.19.ffn_norm.weight": "model-00001-of-00002.safetensors",
126
+ "language_model.model.layers.2.attention.wo.weight": "model-00001-of-00002.safetensors",
127
+ "language_model.model.layers.2.attention.wqkv.weight": "model-00001-of-00002.safetensors",
128
+ "language_model.model.layers.2.attention_norm.weight": "model-00001-of-00002.safetensors",
129
+ "language_model.model.layers.2.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
130
+ "language_model.model.layers.2.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
131
+ "language_model.model.layers.2.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
132
+ "language_model.model.layers.2.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
133
+ "language_model.model.layers.2.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
134
+ "language_model.model.layers.2.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
135
+ "language_model.model.layers.2.ffn_norm.weight": "model-00001-of-00002.safetensors",
136
+ "language_model.model.layers.20.attention.wo.weight": "model-00001-of-00002.safetensors",
137
+ "language_model.model.layers.20.attention.wqkv.weight": "model-00001-of-00002.safetensors",
138
+ "language_model.model.layers.20.attention_norm.weight": "model-00002-of-00002.safetensors",
139
+ "language_model.model.layers.20.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
140
+ "language_model.model.layers.20.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
141
+ "language_model.model.layers.20.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
142
+ "language_model.model.layers.20.feed_forward_ve.w1.weight": "model-00002-of-00002.safetensors",
143
+ "language_model.model.layers.20.feed_forward_ve.w2.weight": "model-00002-of-00002.safetensors",
144
+ "language_model.model.layers.20.feed_forward_ve.w3.weight": "model-00002-of-00002.safetensors",
145
+ "language_model.model.layers.20.ffn_norm.weight": "model-00002-of-00002.safetensors",
146
+ "language_model.model.layers.21.attention.wo.weight": "model-00002-of-00002.safetensors",
147
+ "language_model.model.layers.21.attention.wqkv.weight": "model-00002-of-00002.safetensors",
148
+ "language_model.model.layers.21.attention_norm.weight": "model-00002-of-00002.safetensors",
149
+ "language_model.model.layers.21.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
150
+ "language_model.model.layers.21.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
151
+ "language_model.model.layers.21.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
152
+ "language_model.model.layers.21.feed_forward_ve.w1.weight": "model-00002-of-00002.safetensors",
153
+ "language_model.model.layers.21.feed_forward_ve.w2.weight": "model-00002-of-00002.safetensors",
154
+ "language_model.model.layers.21.feed_forward_ve.w3.weight": "model-00002-of-00002.safetensors",
155
+ "language_model.model.layers.21.ffn_norm.weight": "model-00002-of-00002.safetensors",
156
+ "language_model.model.layers.22.attention.wo.weight": "model-00002-of-00002.safetensors",
157
+ "language_model.model.layers.22.attention.wqkv.weight": "model-00002-of-00002.safetensors",
158
+ "language_model.model.layers.22.attention_norm.weight": "model-00002-of-00002.safetensors",
159
+ "language_model.model.layers.22.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
160
+ "language_model.model.layers.22.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
161
+ "language_model.model.layers.22.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
162
+ "language_model.model.layers.22.feed_forward_ve.w1.weight": "model-00002-of-00002.safetensors",
163
+ "language_model.model.layers.22.feed_forward_ve.w2.weight": "model-00002-of-00002.safetensors",
164
+ "language_model.model.layers.22.feed_forward_ve.w3.weight": "model-00002-of-00002.safetensors",
165
+ "language_model.model.layers.22.ffn_norm.weight": "model-00002-of-00002.safetensors",
166
+ "language_model.model.layers.23.attention.wo.weight": "model-00002-of-00002.safetensors",
167
+ "language_model.model.layers.23.attention.wqkv.weight": "model-00002-of-00002.safetensors",
168
+ "language_model.model.layers.23.attention_norm.weight": "model-00002-of-00002.safetensors",
169
+ "language_model.model.layers.23.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
170
+ "language_model.model.layers.23.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
171
+ "language_model.model.layers.23.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
172
+ "language_model.model.layers.23.feed_forward_ve.w1.weight": "model-00002-of-00002.safetensors",
173
+ "language_model.model.layers.23.feed_forward_ve.w2.weight": "model-00002-of-00002.safetensors",
174
+ "language_model.model.layers.23.feed_forward_ve.w3.weight": "model-00002-of-00002.safetensors",
175
+ "language_model.model.layers.23.ffn_norm.weight": "model-00002-of-00002.safetensors",
176
+ "language_model.model.layers.3.attention.wo.weight": "model-00001-of-00002.safetensors",
177
+ "language_model.model.layers.3.attention.wqkv.weight": "model-00001-of-00002.safetensors",
178
+ "language_model.model.layers.3.attention_norm.weight": "model-00001-of-00002.safetensors",
179
+ "language_model.model.layers.3.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
180
+ "language_model.model.layers.3.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
181
+ "language_model.model.layers.3.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
182
+ "language_model.model.layers.3.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
183
+ "language_model.model.layers.3.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
184
+ "language_model.model.layers.3.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
185
+ "language_model.model.layers.3.ffn_norm.weight": "model-00001-of-00002.safetensors",
186
+ "language_model.model.layers.4.attention.wo.weight": "model-00001-of-00002.safetensors",
187
+ "language_model.model.layers.4.attention.wqkv.weight": "model-00001-of-00002.safetensors",
188
+ "language_model.model.layers.4.attention_norm.weight": "model-00001-of-00002.safetensors",
189
+ "language_model.model.layers.4.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
190
+ "language_model.model.layers.4.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
191
+ "language_model.model.layers.4.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
192
+ "language_model.model.layers.4.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
193
+ "language_model.model.layers.4.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
194
+ "language_model.model.layers.4.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
195
+ "language_model.model.layers.4.ffn_norm.weight": "model-00001-of-00002.safetensors",
196
+ "language_model.model.layers.5.attention.wo.weight": "model-00001-of-00002.safetensors",
197
+ "language_model.model.layers.5.attention.wqkv.weight": "model-00001-of-00002.safetensors",
198
+ "language_model.model.layers.5.attention_norm.weight": "model-00001-of-00002.safetensors",
199
+ "language_model.model.layers.5.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
200
+ "language_model.model.layers.5.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
201
+ "language_model.model.layers.5.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
202
+ "language_model.model.layers.5.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
203
+ "language_model.model.layers.5.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
204
+ "language_model.model.layers.5.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
205
+ "language_model.model.layers.5.ffn_norm.weight": "model-00001-of-00002.safetensors",
206
+ "language_model.model.layers.6.attention.wo.weight": "model-00001-of-00002.safetensors",
207
+ "language_model.model.layers.6.attention.wqkv.weight": "model-00001-of-00002.safetensors",
208
+ "language_model.model.layers.6.attention_norm.weight": "model-00001-of-00002.safetensors",
209
+ "language_model.model.layers.6.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
210
+ "language_model.model.layers.6.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
211
+ "language_model.model.layers.6.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
212
+ "language_model.model.layers.6.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
213
+ "language_model.model.layers.6.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
214
+ "language_model.model.layers.6.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
215
+ "language_model.model.layers.6.ffn_norm.weight": "model-00001-of-00002.safetensors",
216
+ "language_model.model.layers.7.attention.wo.weight": "model-00001-of-00002.safetensors",
217
+ "language_model.model.layers.7.attention.wqkv.weight": "model-00001-of-00002.safetensors",
218
+ "language_model.model.layers.7.attention_norm.weight": "model-00001-of-00002.safetensors",
219
+ "language_model.model.layers.7.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
220
+ "language_model.model.layers.7.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
221
+ "language_model.model.layers.7.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
222
+ "language_model.model.layers.7.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
223
+ "language_model.model.layers.7.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
224
+ "language_model.model.layers.7.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
225
+ "language_model.model.layers.7.ffn_norm.weight": "model-00001-of-00002.safetensors",
226
+ "language_model.model.layers.8.attention.wo.weight": "model-00001-of-00002.safetensors",
227
+ "language_model.model.layers.8.attention.wqkv.weight": "model-00001-of-00002.safetensors",
228
+ "language_model.model.layers.8.attention_norm.weight": "model-00001-of-00002.safetensors",
229
+ "language_model.model.layers.8.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
230
+ "language_model.model.layers.8.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
231
+ "language_model.model.layers.8.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
232
+ "language_model.model.layers.8.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
233
+ "language_model.model.layers.8.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
234
+ "language_model.model.layers.8.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
235
+ "language_model.model.layers.8.ffn_norm.weight": "model-00001-of-00002.safetensors",
236
+ "language_model.model.layers.9.attention.wo.weight": "model-00001-of-00002.safetensors",
237
+ "language_model.model.layers.9.attention.wqkv.weight": "model-00001-of-00002.safetensors",
238
+ "language_model.model.layers.9.attention_norm.weight": "model-00001-of-00002.safetensors",
239
+ "language_model.model.layers.9.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
240
+ "language_model.model.layers.9.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
241
+ "language_model.model.layers.9.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
242
+ "language_model.model.layers.9.feed_forward_ve.w1.weight": "model-00001-of-00002.safetensors",
243
+ "language_model.model.layers.9.feed_forward_ve.w2.weight": "model-00001-of-00002.safetensors",
244
+ "language_model.model.layers.9.feed_forward_ve.w3.weight": "model-00001-of-00002.safetensors",
245
+ "language_model.model.layers.9.ffn_norm.weight": "model-00001-of-00002.safetensors",
246
+ "language_model.model.norm.weight": "model-00002-of-00002.safetensors",
247
+ "language_model.model.tok_embeddings.weight": "model-00001-of-00002.safetensors",
248
+ "language_model.output.weight": "model-00002-of-00002.safetensors",
249
+ "mlp1.0.bias": "model-00002-of-00002.safetensors",
250
+ "mlp1.0.weight": "model-00002-of-00002.safetensors",
251
+ "mlp1.1.bias": "model-00002-of-00002.safetensors",
252
+ "mlp1.1.weight": "model-00002-of-00002.safetensors",
253
+ "mlp1.3.bias": "model-00002-of-00002.safetensors",
254
+ "mlp1.3.weight": "model-00002-of-00002.safetensors",
255
+ "vision_model.embeddings.class_embedding": "model-00001-of-00002.safetensors",
256
+ "vision_model.embeddings.patch_embedding.bias": "model-00001-of-00002.safetensors",
257
+ "vision_model.embeddings.patch_embedding.weight": "model-00001-of-00002.safetensors",
258
+ "vision_model.embeddings.position_embedding": "model-00001-of-00002.safetensors"
259
+ }
260
+ }
modeling_intern_patch.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ from typing import Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from torch import nn
12
+ from transformers.modeling_outputs import (
13
+ BaseModelOutputWithPooling)
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.utils import logging
16
+
17
+ from .configuration_intern_patch import InternVisionPatchConfig
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class InternVisionEmbeddings(nn.Module):
23
+ def __init__(self, config: InternVisionPatchConfig):
24
+ super().__init__()
25
+ self.config = config
26
+ self.embed_dim = config.hidden_size
27
+ self.image_size = config.image_size
28
+ self.patch_size = config.patch_size
29
+
30
+ self.class_embedding = nn.Parameter(
31
+ torch.randn(1, 1, self.embed_dim),
32
+ )
33
+
34
+ self.patch_embedding = nn.Conv2d(
35
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
36
+ )
37
+
38
+ self.num_patches = (self.image_size // self.patch_size) ** 2
39
+ self.num_positions = self.num_patches + 1
40
+
41
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
42
+
43
+ def _get_pos_embed(self, pos_embed, H, W):
44
+ target_dtype = pos_embed.dtype
45
+ pos_embed = pos_embed.float().reshape(
46
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
47
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
48
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
49
+ return pos_embed
50
+
51
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
52
+ target_dtype = self.patch_embedding.weight.dtype
53
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
54
+ batch_size, _, height, width = patch_embeds.shape
55
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
56
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
57
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
58
+ position_embedding = torch.cat([
59
+ self.position_embedding[:, :1, :],
60
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
61
+ ], dim=1)
62
+ embeddings = embeddings + position_embedding.to(target_dtype)
63
+ return embeddings
64
+
65
+
66
+
67
+
68
+
69
+ class InternVisionPatchModel(PreTrainedModel):
70
+ main_input_name = 'pixel_values'
71
+ config_class = InternVisionPatchConfig
72
+ _no_split_modules = ['InternVisionEncoderLayer']
73
+
74
+ def __init__(self, config: InternVisionPatchConfig):
75
+ super().__init__(config)
76
+ self.config = config
77
+ self.embeddings = InternVisionEmbeddings(config)
78
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
79
+ pos_emb = self.embeddings.position_embedding
80
+ _, num_positions, embed_dim = pos_emb.shape
81
+ cls_emb = pos_emb[:, :1, :]
82
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
83
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
84
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
85
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
86
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
87
+ self.embeddings.image_size = new_size
88
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
89
+
90
+ def get_input_embeddings(self):
91
+ return self.embeddings
92
+
93
+
94
+ def forward(
95
+ self,
96
+ pixel_values: Optional[torch.FloatTensor] = None,
97
+ output_hidden_states: Optional[bool] = None,
98
+ return_dict: Optional[bool] = None,
99
+ pixel_embeds: Optional[torch.FloatTensor] = None,
100
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
101
+
102
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
103
+
104
+ if pixel_values is None:
105
+ raise ValueError('You have to specify pixel_values')
106
+
107
+
108
+ if len(pixel_values.shape) == 4:
109
+ hidden_states = self.embeddings(pixel_values)[:,1:]
110
+ else:
111
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
112
+
113
+
114
+ if not return_dict:
115
+ return (hidden_states, None,None)
116
+
117
+ return BaseModelOutputWithPooling(
118
+ last_hidden_state=hidden_states,
119
+ pooler_output=None,
120
+ hidden_states=None,
121
+ attentions=None,
122
+ )
modeling_internlm2_ve.py ADDED
@@ -0,0 +1,1460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch InternLM2 model."""
17
+ import math
18
+ import queue
19
+ import threading
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from einops import rearrange
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ SequenceClassifierOutputWithPast)
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (add_start_docstrings,
35
+ add_start_docstrings_to_model_forward, logging,
36
+ replace_return_docstrings)
37
+
38
+ try:
39
+ from transformers.generation.streamers import BaseStreamer
40
+ except: # noqa # pylint: disable=bare-except
41
+ BaseStreamer = None
42
+
43
+ from .configuration_internlm2 import InternLM2Config
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = 'InternLM2Config'
48
+
49
+ flash_attn_func, flash_attn_varlen_func = None, None
50
+ pad_input, index_first_axis, unpad_input = None, None, None
51
+ try:
52
+ from flash_attn import flash_attn_func as _flash_attn_func
53
+ from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis as _index_first_axis
55
+ from flash_attn.bert_padding import pad_input as _pad_input
56
+ from flash_attn.bert_padding import unpad_input as _unpad_input
57
+
58
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
59
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
60
+ has_flash_attn = True
61
+ except:
62
+ has_flash_attn = False
63
+
64
+
65
+ def _import_flash_attn():
66
+ global flash_attn_func, flash_attn_varlen_func
67
+ global pad_input, index_first_axis, unpad_input
68
+ try:
69
+ from flash_attn import flash_attn_func as _flash_attn_func
70
+ from flash_attn import \
71
+ flash_attn_varlen_func as _flash_attn_varlen_func
72
+ from flash_attn.bert_padding import \
73
+ index_first_axis as _index_first_axis
74
+ from flash_attn.bert_padding import pad_input as _pad_input
75
+ from flash_attn.bert_padding import unpad_input as _unpad_input
76
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
77
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
78
+ except ImportError:
79
+ raise ImportError('flash_attn is not installed.')
80
+
81
+
82
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
83
+ def _get_unpad_data(attention_mask):
84
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
85
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
86
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
87
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
88
+ return (
89
+ indices,
90
+ cu_seqlens,
91
+ max_seqlen_in_batch,
92
+ )
93
+
94
+
95
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
96
+ def _make_causal_mask(
97
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
98
+ ):
99
+ """
100
+ Make causal mask used for bi-directional self-attention.
101
+ """
102
+ bsz, tgt_len = input_ids_shape
103
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
104
+ mask_cond = torch.arange(mask.size(-1), device=device)
105
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
106
+ mask = mask.to(dtype)
107
+
108
+ if past_key_values_length > 0:
109
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
110
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
111
+
112
+
113
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
114
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
115
+ """
116
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
117
+ """
118
+ bsz, src_len = mask.size()
119
+ tgt_len = tgt_len if tgt_len is not None else src_len
120
+
121
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
122
+
123
+ inverted_mask = 1.0 - expanded_mask
124
+
125
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
126
+
127
+
128
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
129
+ class InternLM2RMSNorm(nn.Module):
130
+ def __init__(self, hidden_size, eps=1e-6):
131
+ """
132
+ InternLM2RMSNorm is equivalent to T5LayerNorm
133
+ """
134
+ super().__init__()
135
+ self.weight = nn.Parameter(torch.ones(hidden_size))
136
+ self.variance_epsilon = eps
137
+
138
+ def forward(self, hidden_states):
139
+ input_dtype = hidden_states.dtype
140
+ hidden_states = hidden_states.to(torch.float32)
141
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
142
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
143
+ return self.weight * hidden_states.to(input_dtype)
144
+
145
+
146
+ try:
147
+ from functools import partial
148
+
149
+ from apex.normalization import FusedRMSNorm
150
+ InternLM2RMSNorm = partial(FusedRMSNorm, eps=1e-6) # noqa
151
+ print('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternLM2RMSNorm')
152
+ except ImportError:
153
+ # using the normal LlamaRMSNorm
154
+ pass
155
+ except Exception:
156
+ print('discovered apex but it failed to load, falling back to InternLM2RMSNorm')
157
+ pass
158
+
159
+
160
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
161
+ class InternLM2RotaryEmbedding(nn.Module):
162
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
163
+ super().__init__()
164
+
165
+ self.dim = dim
166
+ self.max_position_embeddings = max_position_embeddings
167
+ self.base = base
168
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
169
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
170
+
171
+ # Build here to make `torch.jit.trace` work.
172
+ self._set_cos_sin_cache(
173
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
174
+ )
175
+
176
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
177
+ self.max_seq_len_cached = seq_len
178
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
179
+
180
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
181
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
182
+ emb = torch.cat((freqs, freqs), dim=-1)
183
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
184
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
185
+
186
+ def forward(self, x, seq_len=None):
187
+ # x: [bs, num_attention_heads, seq_len, head_size]
188
+ if seq_len > self.max_seq_len_cached:
189
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
190
+
191
+ return (
192
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
193
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
194
+ )
195
+
196
+
197
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
198
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
199
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
200
+
201
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
202
+ self.scaling_factor = scaling_factor
203
+ super().__init__(dim, max_position_embeddings, base, device)
204
+
205
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
206
+ self.max_seq_len_cached = seq_len
207
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
208
+ t = t / self.scaling_factor
209
+
210
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
211
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
212
+ emb = torch.cat((freqs, freqs), dim=-1)
213
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
214
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
215
+
216
+
217
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
218
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
219
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
220
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
221
+ """
222
+
223
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
224
+ self.scaling_factor = scaling_factor
225
+ super().__init__(dim, max_position_embeddings, base, device)
226
+
227
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
228
+ self.max_seq_len_cached = seq_len
229
+
230
+ if seq_len > self.max_position_embeddings:
231
+ base = self.base * (
232
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
233
+ ) ** (self.dim / (self.dim - 2))
234
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
235
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
236
+
237
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
238
+
239
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
240
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
241
+ emb = torch.cat((freqs, freqs), dim=-1)
242
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
243
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
244
+
245
+
246
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
247
+ def rotate_half(x):
248
+ """Rotates half the hidden dims of the input."""
249
+ x1 = x[..., : x.shape[-1] // 2]
250
+ x2 = x[..., x.shape[-1] // 2:]
251
+ return torch.cat((-x2, x1), dim=-1)
252
+
253
+
254
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
255
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
256
+ """Applies Rotary Position Embedding to the query and key tensors."""
257
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
258
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
259
+ q_embed = (q * cos) + (rotate_half(q) * sin)
260
+ k_embed = (k * cos) + (rotate_half(k) * sin)
261
+ return q_embed, k_embed
262
+
263
+
264
+ class InternLM2MLP(nn.Module):
265
+ def __init__(self, config):
266
+ super().__init__()
267
+ self.config = config
268
+ self.hidden_size = config.hidden_size
269
+ self.intermediate_size = config.intermediate_size
270
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
271
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
272
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
273
+ self.act_fn = ACT2FN[config.hidden_act]
274
+
275
+ def forward(self, x):
276
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
277
+
278
+ return down_proj
279
+
280
+
281
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
282
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
283
+ """
284
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
285
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
286
+ """
287
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
288
+ if n_rep == 1:
289
+ return hidden_states
290
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
291
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
292
+
293
+
294
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
295
+ class InternLM2Attention(nn.Module):
296
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
297
+
298
+ def __init__(self, config: InternLM2Config):
299
+ super().__init__()
300
+ self.config = config
301
+ self.hidden_size = config.hidden_size
302
+ self.num_heads = config.num_attention_heads
303
+ self.head_dim = self.hidden_size // self.num_heads
304
+ self.num_key_value_heads = config.num_key_value_heads
305
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
306
+ self.max_position_embeddings = config.max_position_embeddings
307
+ self.is_causal = True
308
+
309
+ if (self.head_dim * self.num_heads) != self.hidden_size:
310
+ raise ValueError(
311
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
312
+ f' and `num_heads`: {self.num_heads}).'
313
+ )
314
+
315
+ self.wqkv = nn.Linear(
316
+ self.hidden_size,
317
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
318
+ bias=config.bias,
319
+ )
320
+
321
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
322
+ self._init_rope()
323
+
324
+ def _init_rope(self):
325
+ if self.config.rope_scaling is None:
326
+ self.rotary_emb = InternLM2RotaryEmbedding(
327
+ self.head_dim,
328
+ max_position_embeddings=self.max_position_embeddings,
329
+ base=self.config.rope_theta,
330
+ )
331
+ else:
332
+ scaling_type = self.config.rope_scaling['type']
333
+ scaling_factor = self.config.rope_scaling['factor']
334
+ if scaling_type == 'dynamic':
335
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
336
+ self.head_dim,
337
+ max_position_embeddings=self.max_position_embeddings,
338
+ base=self.config.rope_theta,
339
+ scaling_factor=scaling_factor,
340
+ )
341
+ elif scaling_type == 'linear':
342
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
343
+ self.head_dim,
344
+ max_position_embeddings=self.max_position_embeddings,
345
+ base=self.config.rope_theta,
346
+ scaling_factor=scaling_factor,
347
+ )
348
+ else:
349
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
350
+ return self.rotary_emb
351
+
352
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
353
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
354
+
355
+ def forward(
356
+ self,
357
+ hidden_states: torch.Tensor,
358
+ attention_mask: Optional[torch.Tensor] = None,
359
+ position_ids: Optional[torch.LongTensor] = None,
360
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
361
+ output_attentions: bool = False,
362
+ use_cache: bool = False,
363
+ **kwargs,
364
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
365
+ if 'padding_mask' in kwargs:
366
+ warnings.warn(
367
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
368
+ 'Please make sure use `attention_mask` instead.`'
369
+ )
370
+
371
+ bsz, q_len, _ = hidden_states.size()
372
+
373
+ qkv_states = self.wqkv(hidden_states)
374
+
375
+ qkv_states = rearrange(
376
+ qkv_states,
377
+ 'b q (h gs d) -> b q h gs d',
378
+ gs=2 + self.num_key_value_groups,
379
+ d=self.head_dim,
380
+ )
381
+
382
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
383
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
384
+ key_states = qkv_states[..., -2, :]
385
+ value_states = qkv_states[..., -1, :]
386
+
387
+ query_states = query_states.transpose(1, 2)
388
+ key_states = key_states.transpose(1, 2)
389
+ value_states = value_states.transpose(1, 2)
390
+
391
+ kv_seq_len = key_states.shape[-2]
392
+ if past_key_value is not None:
393
+ kv_seq_len += past_key_value[0].shape[-2]
394
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
395
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
396
+
397
+ if past_key_value is not None:
398
+ # reuse k, v, self_attention
399
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
400
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
401
+
402
+ past_key_value = (key_states, value_states) if use_cache else None
403
+
404
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
405
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
406
+
407
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
408
+
409
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
410
+ raise ValueError(
411
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
412
+ f' {attn_weights.size()}'
413
+ )
414
+
415
+ if attention_mask is not None:
416
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
417
+ raise ValueError(
418
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
419
+ )
420
+ attn_weights = attn_weights + attention_mask
421
+
422
+ # upcast attention to fp32
423
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
424
+ attn_output = torch.matmul(attn_weights, value_states)
425
+
426
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
427
+ raise ValueError(
428
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
429
+ f' {attn_output.size()}'
430
+ )
431
+
432
+ attn_output = attn_output.transpose(1, 2).contiguous()
433
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
434
+
435
+ attn_output = self.wo(attn_output)
436
+
437
+ if not output_attentions:
438
+ attn_weights = None
439
+
440
+ return attn_output, attn_weights, past_key_value
441
+
442
+
443
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
444
+ class InternLM2FlashAttention2(InternLM2Attention):
445
+ """
446
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
447
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
448
+ flash attention and deal with padding tokens in case the input contains any of them.
449
+ """
450
+
451
+ def forward(
452
+ self,
453
+ hidden_states: torch.Tensor,
454
+ attention_mask: Optional[torch.LongTensor] = None,
455
+ position_ids: Optional[torch.LongTensor] = None,
456
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
457
+ output_attentions: bool = False,
458
+ use_cache: bool = False,
459
+ **kwargs,
460
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
461
+ # InternLM2FlashAttention2 attention does not support output_attentions
462
+ if 'padding_mask' in kwargs:
463
+ warnings.warn(
464
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
465
+ 'Please make sure use `attention_mask` instead.`'
466
+ )
467
+
468
+ # overwrite attention_mask with padding_mask
469
+ attention_mask = kwargs.pop('padding_mask')
470
+
471
+ output_attentions = False
472
+
473
+ bsz, q_len, _ = hidden_states.size()
474
+
475
+ qkv_states = self.wqkv(hidden_states)
476
+
477
+ qkv_states = rearrange(
478
+ qkv_states,
479
+ 'b q (h gs d) -> b q h gs d',
480
+ gs=2 + self.num_key_value_groups,
481
+ d=self.head_dim,
482
+ )
483
+
484
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
485
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
486
+ key_states = qkv_states[..., -2, :]
487
+ value_states = qkv_states[..., -1, :]
488
+
489
+ query_states = query_states.transpose(1, 2)
490
+ key_states = key_states.transpose(1, 2)
491
+ value_states = value_states.transpose(1, 2)
492
+
493
+ kv_seq_len = key_states.shape[-2]
494
+ if past_key_value is not None:
495
+ kv_seq_len += past_key_value[0].shape[-2]
496
+
497
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
498
+
499
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
500
+
501
+ if past_key_value is not None:
502
+ # reuse k, v, self_attention
503
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
504
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
505
+
506
+ past_key_value = (key_states, value_states) if use_cache else None
507
+
508
+ query_states = query_states.transpose(1, 2)
509
+ key_states = key_states.transpose(1, 2)
510
+ value_states = value_states.transpose(1, 2)
511
+
512
+ attn_output = self._flash_attention_forward(
513
+ query_states, key_states, value_states, attention_mask, q_len
514
+ )
515
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
516
+ attn_output = self.wo(attn_output)
517
+
518
+ if not output_attentions:
519
+ attn_weights = None
520
+
521
+ return attn_output, attn_weights, past_key_value
522
+
523
+ def _flash_attention_forward(
524
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
525
+ ):
526
+ """
527
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
528
+ first unpad the input, then computes the attention scores and pad the final attention scores.
529
+
530
+ Args:
531
+ query_states (`torch.Tensor`):
532
+ Input query states to be passed to Flash Attention API
533
+ key_states (`torch.Tensor`):
534
+ Input key states to be passed to Flash Attention API
535
+ value_states (`torch.Tensor`):
536
+ Input value states to be passed to Flash Attention API
537
+ attention_mask (`torch.Tensor`):
538
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
539
+ position of padding tokens and 1 for the position of non-padding tokens.
540
+ dropout (`int`, *optional*):
541
+ Attention dropout
542
+ softmax_scale (`float`, *optional*):
543
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
544
+ """
545
+ # Contains at least one padding token in the sequence
546
+ causal = self.is_causal and query_length != 1
547
+ if attention_mask is not None:
548
+ batch_size = query_states.shape[0]
549
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
550
+ query_states, key_states, value_states, attention_mask, query_length
551
+ )
552
+
553
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
554
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
555
+
556
+ attn_output_unpad = flash_attn_varlen_func(
557
+ query_states,
558
+ key_states,
559
+ value_states,
560
+ cu_seqlens_q=cu_seqlens_q,
561
+ cu_seqlens_k=cu_seqlens_k,
562
+ max_seqlen_q=max_seqlen_in_batch_q,
563
+ max_seqlen_k=max_seqlen_in_batch_k,
564
+ dropout_p=dropout,
565
+ softmax_scale=softmax_scale,
566
+ causal=causal,
567
+ )
568
+
569
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
570
+ else:
571
+ attn_output = flash_attn_func(
572
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
573
+ )
574
+
575
+ return attn_output
576
+
577
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
578
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
579
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
580
+
581
+ key_layer = index_first_axis(
582
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
583
+ )
584
+ value_layer = index_first_axis(
585
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
586
+ )
587
+
588
+ if query_length == kv_seq_len:
589
+ query_layer = index_first_axis(
590
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
591
+ )
592
+ cu_seqlens_q = cu_seqlens_k
593
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
594
+ indices_q = indices_k
595
+ elif query_length == 1:
596
+ max_seqlen_in_batch_q = 1
597
+ cu_seqlens_q = torch.arange(
598
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
599
+ ) # There is a memcpy here, that is very bad.
600
+ indices_q = cu_seqlens_q[:-1]
601
+ query_layer = query_layer.squeeze(1)
602
+ else:
603
+ # The -q_len: slice assumes left padding.
604
+ attention_mask = attention_mask[:, -query_length:]
605
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
606
+
607
+ return (
608
+ query_layer,
609
+ key_layer,
610
+ value_layer,
611
+ indices_q.to(torch.int64),
612
+ (cu_seqlens_q, cu_seqlens_k),
613
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
614
+ )
615
+
616
+
617
+ INTERNLM2_ATTENTION_CLASSES = {
618
+ 'eager': InternLM2Attention,
619
+ 'flash_attention_2': InternLM2FlashAttention2,
620
+ }
621
+
622
+
623
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
624
+ class InternLM2DecoderLayer(nn.Module):
625
+ def __init__(self, config: InternLM2Config):
626
+ super().__init__()
627
+ self.hidden_size = config.hidden_size
628
+
629
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
630
+
631
+ self.feed_forward = InternLM2MLP(config)
632
+ #visual expert copied from self.feed_forward
633
+ self.feed_forward_ve = InternLM2MLP(config)
634
+
635
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
636
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
637
+
638
+ def forward(
639
+ self,
640
+ hidden_states: torch.Tensor,
641
+ attention_mask: Optional[torch.Tensor] = None,
642
+ position_ids: Optional[torch.LongTensor] = None,
643
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
644
+ output_attentions: Optional[bool] = False,
645
+ use_cache: Optional[bool] = False,
646
+ visual_token_mask: Optional[torch.Tensor] = None,
647
+ **kwargs,
648
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
649
+ """
650
+ Args:
651
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
652
+ attention_mask (`torch.FloatTensor`, *optional*):
653
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
654
+ query_sequence_length, key_sequence_length)` if default attention is used.
655
+ output_attentions (`bool`, *optional*):
656
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
657
+ returned tensors for more detail.
658
+ use_cache (`bool`, *optional*):
659
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
660
+ (see `past_key_values`).
661
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
662
+ """
663
+ # print(visual_token_mask,past_key_value)
664
+ assert visual_token_mask is not None or past_key_value is not None
665
+ if 'padding_mask' in kwargs:
666
+ warnings.warn(
667
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
668
+ 'Please make sure use `attention_mask` instead.`'
669
+ )
670
+
671
+ residual = hidden_states
672
+
673
+ hidden_states = self.attention_norm(hidden_states)
674
+
675
+ # Self Attention
676
+ hidden_states, self_attn_weights, present_key_value = self.attention(
677
+ hidden_states=hidden_states,
678
+ attention_mask=attention_mask,
679
+ position_ids=position_ids,
680
+ past_key_value=past_key_value,
681
+ output_attentions=output_attentions,
682
+ use_cache=use_cache,
683
+ **kwargs,
684
+ )
685
+ hidden_states = residual + hidden_states
686
+
687
+ # Fully Connected
688
+ residual = hidden_states
689
+ hidden_states = self.ffn_norm(hidden_states)
690
+
691
+ if past_key_value is None:
692
+ """
693
+ *************************
694
+ maybe faster
695
+ ***************************
696
+ """
697
+ ##############################################################################################################
698
+ # dim=hidden_states.shape[-1]
699
+ # visual_token_mask=visual_token_mask.repeat(1,1,dim)
700
+ # if visual_token_mask.any():
701
+ # hidden_states[visual_token_mask] = self.feed_forward_ve(hidden_states[visual_token_mask].reshape(-1,dim)).reshape(-1)
702
+ # if (~visual_token_mask).any():
703
+ # hidden_states[~visual_token_mask] = self.feed_forward(hidden_states[~visual_token_mask].reshape(-1,dim)).reshape(-1)
704
+ ##############################################################################################################
705
+ hidden_states = self.feed_forward(hidden_states)*(1.-visual_token_mask)+ self.feed_forward_ve(hidden_states)*visual_token_mask
706
+ else:
707
+ hidden_states = self.feed_forward(hidden_states)
708
+
709
+ hidden_states = residual + hidden_states
710
+
711
+ outputs = (hidden_states,)
712
+
713
+ if output_attentions:
714
+ outputs += (self_attn_weights,)
715
+
716
+ if use_cache:
717
+ outputs += (present_key_value,)
718
+
719
+ return outputs
720
+
721
+
722
+ InternLM2_START_DOCSTRING = r"""
723
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
724
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
725
+ etc.)
726
+
727
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
728
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
729
+ and behavior.
730
+
731
+ Parameters:
732
+ config ([`InternLM2Config`]):
733
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
734
+ load the weights associated with the model, only the configuration. Check out the
735
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
736
+ """
737
+
738
+
739
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
740
+ @add_start_docstrings(
741
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
742
+ InternLM2_START_DOCSTRING,
743
+ )
744
+ class InternLM2PreTrainedModel(PreTrainedModel):
745
+ config_class = InternLM2Config
746
+ base_model_prefix = 'model'
747
+ supports_gradient_checkpointing = True
748
+ _no_split_modules = ['InternLM2DecoderLayer']
749
+ _skip_keys_device_placement = 'past_key_values'
750
+
751
+ def _init_weights(self, module):
752
+ std = self.config.initializer_range
753
+ if isinstance(module, nn.Linear):
754
+ module.weight.data.normal_(mean=0.0, std=std)
755
+ if module.bias is not None:
756
+ module.bias.data.zero_()
757
+ elif isinstance(module, nn.Embedding):
758
+ module.weight.data.normal_(mean=0.0, std=std)
759
+ if module.padding_idx is not None:
760
+ module.weight.data[module.padding_idx].zero_()
761
+
762
+
763
+ InternLM2_INPUTS_DOCSTRING = r"""
764
+ Args:
765
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
766
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
767
+ it.
768
+
769
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
770
+ [`PreTrainedTokenizer.__call__`] for details.
771
+
772
+ [What are input IDs?](../glossary#input-ids)
773
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
774
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
775
+
776
+ - 1 for tokens that are **not masked**,
777
+ - 0 for tokens that are **masked**.
778
+
779
+ [What are attention masks?](../glossary#attention-mask)
780
+
781
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
782
+ [`PreTrainedTokenizer.__call__`] for details.
783
+
784
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
785
+ `past_key_values`).
786
+
787
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
788
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
789
+ information on the default strategy.
790
+
791
+ - 1 indicates the head is **not masked**,
792
+ - 0 indicates the head is **masked**.
793
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
794
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
795
+ config.n_positions - 1]`.
796
+
797
+ [What are position IDs?](../glossary#position-ids)
798
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
799
+ when `config.use_cache=True`):
800
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
801
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
802
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
803
+
804
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
805
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
806
+
807
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
808
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
809
+ of shape `(batch_size, sequence_length)`.
810
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
811
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
812
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
813
+ model's internal embedding lookup matrix.
814
+ use_cache (`bool`, *optional*):
815
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
816
+ `past_key_values`).
817
+ output_attentions (`bool`, *optional*):
818
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
819
+ tensors for more detail.
820
+ output_hidden_states (`bool`, *optional*):
821
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
822
+ more detail.
823
+ return_dict (`bool`, *optional*):
824
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
825
+ """
826
+
827
+
828
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
829
+ @add_start_docstrings(
830
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
831
+ InternLM2_START_DOCSTRING,
832
+ )
833
+ class InternLM2Model(InternLM2PreTrainedModel):
834
+ """
835
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
836
+
837
+ Args:
838
+ config: InternLM2Config
839
+ """
840
+
841
+ _auto_class = 'AutoModel'
842
+
843
+ def __init__(self, config: InternLM2Config):
844
+ super().__init__(config)
845
+ self.padding_idx = config.pad_token_id
846
+ self.vocab_size = config.vocab_size
847
+ self.config = config
848
+ if not has_flash_attn:
849
+ self.config.attn_implementation = 'eager'
850
+ print('Warning: Flash attention is not available, using eager attention instead.')
851
+
852
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
853
+
854
+ self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
855
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
856
+
857
+ self.gradient_checkpointing = False
858
+ # Initialize weights and apply final processing
859
+ self.post_init()
860
+
861
+ def get_input_embeddings(self):
862
+ return self.tok_embeddings
863
+
864
+ def set_input_embeddings(self, value):
865
+ self.tok_embeddings = value
866
+
867
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
868
+ # create causal mask
869
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
870
+ combined_attention_mask = None
871
+ if input_shape[-1] > 1:
872
+ combined_attention_mask = _make_causal_mask(
873
+ input_shape,
874
+ inputs_embeds.dtype,
875
+ device=inputs_embeds.device,
876
+ past_key_values_length=past_key_values_length,
877
+ )
878
+
879
+ if attention_mask is not None:
880
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
881
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
882
+ inputs_embeds.device
883
+ )
884
+ combined_attention_mask = (
885
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
886
+ )
887
+
888
+ return combined_attention_mask
889
+
890
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
891
+ def forward(
892
+ self,
893
+ input_ids: torch.LongTensor = None,
894
+ attention_mask: Optional[torch.Tensor] = None,
895
+ position_ids: Optional[torch.LongTensor] = None,
896
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
897
+ inputs_embeds: Optional[torch.FloatTensor] = None,
898
+ use_cache: Optional[bool] = None,
899
+ output_attentions: Optional[bool] = None,
900
+ output_hidden_states: Optional[bool] = None,
901
+ return_dict: Optional[bool] = None,
902
+ visual_token_mask: Optional[torch.Tensor] = None
903
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
904
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
905
+ output_hidden_states = (
906
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
907
+ )
908
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
909
+
910
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
911
+
912
+ if self.config.attn_implementation == 'flash_attention_2':
913
+ _import_flash_attn()
914
+
915
+ # retrieve input_ids and inputs_embeds
916
+ if input_ids is not None and inputs_embeds is not None:
917
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
918
+ elif input_ids is not None:
919
+ batch_size, seq_length = input_ids.shape[:2]
920
+ elif inputs_embeds is not None:
921
+ batch_size, seq_length = inputs_embeds.shape[:2]
922
+ else:
923
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
924
+
925
+ seq_length_with_past = seq_length
926
+ past_key_values_length = 0
927
+ if past_key_values is not None:
928
+ past_key_values_length = past_key_values[0][0].shape[2]
929
+ seq_length_with_past = seq_length_with_past + past_key_values_length
930
+
931
+ if position_ids is None:
932
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
933
+ position_ids = torch.arange(
934
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
935
+ )
936
+ position_ids = position_ids.unsqueeze(0)
937
+
938
+ if inputs_embeds is None:
939
+ inputs_embeds = self.tok_embeddings(input_ids)
940
+
941
+ if self.config.attn_implementation == 'flash_attention_2':
942
+ # 2d mask is passed through the layers
943
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
944
+ else:
945
+ if attention_mask is None:
946
+ attention_mask = torch.ones(
947
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
948
+ )
949
+ attention_mask = self._prepare_decoder_attention_mask(
950
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
951
+ )
952
+
953
+ # embed positions
954
+ hidden_states = inputs_embeds
955
+
956
+ if self.gradient_checkpointing and self.training:
957
+ if use_cache:
958
+ logger.warning_once(
959
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
960
+ )
961
+ use_cache = False
962
+
963
+ # decoder layers
964
+ all_hidden_states = () if output_hidden_states else None
965
+ all_self_attns = () if output_attentions else None
966
+ next_decoder_cache = () if use_cache else None
967
+
968
+ for idx, decoder_layer in enumerate(self.layers):
969
+ if output_hidden_states:
970
+ all_hidden_states += (hidden_states,)
971
+
972
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
973
+
974
+ if self.gradient_checkpointing and self.training:
975
+
976
+ def create_custom_forward(module):
977
+ def custom_forward(*inputs):
978
+ # None for past_key_value
979
+ return module(*inputs[:-1], output_attentions, None, visual_token_mask=inputs[-1])
980
+
981
+ return custom_forward
982
+
983
+ layer_outputs = torch.utils.checkpoint.checkpoint(
984
+ create_custom_forward(decoder_layer),
985
+ hidden_states,
986
+ attention_mask,
987
+ position_ids,
988
+ None,
989
+ visual_token_mask
990
+ )
991
+ else:
992
+ layer_outputs = decoder_layer(
993
+ hidden_states,
994
+ attention_mask=attention_mask,
995
+ position_ids=position_ids,
996
+ past_key_value=past_key_value,
997
+ output_attentions=output_attentions,
998
+ use_cache=use_cache,
999
+ visual_token_mask=visual_token_mask
1000
+ )
1001
+
1002
+ hidden_states = layer_outputs[0]
1003
+
1004
+ if use_cache:
1005
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1006
+
1007
+ if output_attentions:
1008
+ all_self_attns += (layer_outputs[1],)
1009
+
1010
+ hidden_states = self.norm(hidden_states)
1011
+
1012
+ # add hidden states from the last decoder layer
1013
+ if output_hidden_states:
1014
+ all_hidden_states += (hidden_states,)
1015
+
1016
+ next_cache = next_decoder_cache if use_cache else None
1017
+ if not return_dict:
1018
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1019
+ return BaseModelOutputWithPast(
1020
+ last_hidden_state=hidden_states,
1021
+ past_key_values=next_cache,
1022
+ hidden_states=all_hidden_states,
1023
+ attentions=all_self_attns,
1024
+ )
1025
+
1026
+
1027
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
1028
+ class InternLM2VEForCausalLM(InternLM2PreTrainedModel):
1029
+ _auto_class = 'AutoModelForCausalLM'
1030
+
1031
+ _tied_weights_keys = ['output.weight']
1032
+
1033
+ def __init__(self, config):
1034
+ super().__init__(config)
1035
+ self.model = InternLM2Model(config)
1036
+ self.vocab_size = config.vocab_size
1037
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1038
+
1039
+ # Initialize weights and apply final processing
1040
+ self.post_init()
1041
+
1042
+ def get_input_embeddings(self):
1043
+ return self.model.tok_embeddings
1044
+
1045
+ def set_input_embeddings(self, value):
1046
+ self.model.tok_embeddings = value
1047
+
1048
+ def get_output_embeddings(self):
1049
+ return self.output
1050
+
1051
+ def set_output_embeddings(self, new_embeddings):
1052
+ self.output = new_embeddings
1053
+
1054
+ def set_decoder(self, decoder):
1055
+ self.model = decoder
1056
+
1057
+ def get_decoder(self):
1058
+ return self.model
1059
+
1060
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1061
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1062
+ def forward(
1063
+ self,
1064
+ input_ids: torch.LongTensor = None,
1065
+ attention_mask: Optional[torch.Tensor] = None,
1066
+ position_ids: Optional[torch.LongTensor] = None,
1067
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1068
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1069
+ labels: Optional[torch.LongTensor] = None,
1070
+ use_cache: Optional[bool] = None,
1071
+ output_attentions: Optional[bool] = None,
1072
+ output_hidden_states: Optional[bool] = None,
1073
+ return_dict: Optional[bool] = None,
1074
+ visual_token_mask: Optional[torch.Tensor] = None
1075
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1076
+ r"""
1077
+ Args:
1078
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1079
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1080
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1081
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1082
+
1083
+ Returns:
1084
+
1085
+ Example:
1086
+
1087
+ ```python
1088
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1089
+
1090
+ >>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1091
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1092
+
1093
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1094
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1095
+
1096
+ >>> # Generate
1097
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1098
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1099
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1100
+ ```"""
1101
+
1102
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1103
+ output_hidden_states = (
1104
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1105
+ )
1106
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1107
+
1108
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1109
+ outputs = self.model(
1110
+ input_ids=input_ids,
1111
+ attention_mask=attention_mask,
1112
+ position_ids=position_ids,
1113
+ past_key_values=past_key_values,
1114
+ inputs_embeds=inputs_embeds,
1115
+ use_cache=use_cache,
1116
+ output_attentions=output_attentions,
1117
+ output_hidden_states=output_hidden_states,
1118
+ return_dict=return_dict,
1119
+ visual_token_mask=visual_token_mask
1120
+ )
1121
+
1122
+ hidden_states = outputs[0]
1123
+ logits = self.output(hidden_states)
1124
+ logits = logits.float()
1125
+
1126
+ loss = None
1127
+ if labels is not None:
1128
+ # Shift so that tokens < n predict n
1129
+ shift_logits = logits[..., :-1, :].contiguous()
1130
+ shift_labels = labels[..., 1:].contiguous()
1131
+ # Flatten the tokens
1132
+ loss_fct = CrossEntropyLoss()
1133
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1134
+ shift_labels = shift_labels.view(-1)
1135
+ # Enable model parallelism
1136
+ shift_labels = shift_labels.to(shift_logits.device)
1137
+ loss = loss_fct(shift_logits, shift_labels)
1138
+
1139
+ if not return_dict:
1140
+ output = (logits,) + outputs[1:]
1141
+ return (loss,) + output if loss is not None else output
1142
+
1143
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1144
+ output = CausalLMOutputWithPast(
1145
+ loss=loss,
1146
+ logits=logits,
1147
+ past_key_values=outputs.past_key_values,
1148
+ hidden_states=outputs.hidden_states,
1149
+ attentions=outputs.attentions,
1150
+ )
1151
+ output['logits'] = output['logits'].to(device)
1152
+ return output
1153
+
1154
+ def prepare_inputs_for_generation(
1155
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1156
+ ):
1157
+ if past_key_values is not None:
1158
+ past_length = past_key_values[0][0].shape[2]
1159
+
1160
+ # Some generation methods already pass only the last input ID
1161
+ if input_ids.shape[1] > past_length:
1162
+ remove_prefix_length = past_length
1163
+ else:
1164
+ # Default to old behavior: keep only final ID
1165
+ remove_prefix_length = input_ids.shape[1] - 1
1166
+
1167
+ input_ids = input_ids[:, remove_prefix_length:]
1168
+
1169
+ position_ids = kwargs.get('position_ids', None)
1170
+ if attention_mask is not None and position_ids is None:
1171
+ # create position_ids on the fly for batch generation
1172
+ position_ids = attention_mask.long().cumsum(-1) - 1
1173
+ position_ids.masked_fill_(attention_mask == 0, 1)
1174
+ if past_key_values:
1175
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1176
+
1177
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1178
+ if inputs_embeds is not None and past_key_values is None:
1179
+ model_inputs = {'inputs_embeds': inputs_embeds}
1180
+ else:
1181
+ model_inputs = {'input_ids': input_ids}
1182
+
1183
+ model_inputs.update(
1184
+ {
1185
+ 'position_ids': position_ids,
1186
+ 'past_key_values': past_key_values,
1187
+ 'use_cache': kwargs.get('use_cache'),
1188
+ 'attention_mask': attention_mask,
1189
+ 'visual_token_mask': kwargs.get('visual_token_mask')
1190
+ }
1191
+ )
1192
+ return model_inputs
1193
+
1194
+ @staticmethod
1195
+ def _reorder_cache(past_key_values, beam_idx):
1196
+ reordered_past = ()
1197
+ for layer_past in past_key_values:
1198
+ reordered_past += (
1199
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1200
+ )
1201
+ return reordered_past
1202
+
1203
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=''):
1204
+ if tokenizer.add_bos_token:
1205
+ prompt = ''
1206
+ else:
1207
+ prompt = tokenizer.bos_token
1208
+ if meta_instruction:
1209
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1210
+ for record in history:
1211
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1212
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1213
+ return tokenizer([prompt], return_tensors='pt')
1214
+
1215
+ @torch.no_grad()
1216
+ def chat(
1217
+ self,
1218
+ tokenizer,
1219
+ query: str,
1220
+ history: List[Tuple[str, str]] = [],
1221
+ streamer: Optional[BaseStreamer] = None,
1222
+ max_new_tokens: int = 1024,
1223
+ do_sample: bool = True,
1224
+ temperature: float = 0.8,
1225
+ top_p: float = 0.8,
1226
+ meta_instruction: str = 'You are an AI assistant whose name is InternLM (书生·浦语).\n'
1227
+ '- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n'
1228
+ '- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.',
1229
+ **kwargs,
1230
+ ):
1231
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1232
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1233
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1234
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(['<|im_end|>'])[0]]
1235
+ outputs = self.generate(
1236
+ **inputs,
1237
+ streamer=streamer,
1238
+ max_new_tokens=max_new_tokens,
1239
+ do_sample=do_sample,
1240
+ temperature=temperature,
1241
+ top_p=top_p,
1242
+ eos_token_id=eos_token_id,
1243
+ **kwargs,
1244
+ )
1245
+ outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]):]
1246
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1247
+ response = response.split('<|im_end|>')[0]
1248
+ history = history + [(query, response)]
1249
+ return response, history
1250
+
1251
+ @torch.no_grad()
1252
+ def stream_chat(
1253
+ self,
1254
+ tokenizer,
1255
+ query: str,
1256
+ history: List[Tuple[str, str]] = [],
1257
+ max_new_tokens: int = 1024,
1258
+ do_sample: bool = True,
1259
+ temperature: float = 0.8,
1260
+ top_p: float = 0.8,
1261
+ **kwargs,
1262
+ ):
1263
+ """
1264
+ Return a generator in format: (response, history)
1265
+ Eg.
1266
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1267
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1268
+ """
1269
+ if BaseStreamer is None:
1270
+ raise ModuleNotFoundError(
1271
+ 'The version of `transformers` is too low. Please make sure '
1272
+ 'that you have installed `transformers>=4.28.0`.'
1273
+ )
1274
+
1275
+ response_queue = queue.Queue(maxsize=20)
1276
+
1277
+ class ChatStreamer(BaseStreamer):
1278
+ def __init__(self, tokenizer) -> None:
1279
+ super().__init__()
1280
+ self.tokenizer = tokenizer
1281
+ self.queue = response_queue
1282
+ self.query = query
1283
+ self.history = history
1284
+ self.response = ''
1285
+ self.cache = []
1286
+ self.received_inputs = False
1287
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1288
+
1289
+ def put(self, value):
1290
+ if len(value.shape) > 1 and value.shape[0] > 1:
1291
+ raise ValueError('ChatStreamer only supports batch size 1')
1292
+ elif len(value.shape) > 1:
1293
+ value = value[0]
1294
+
1295
+ if not self.received_inputs:
1296
+ # The first received value is input_ids, ignore here
1297
+ self.received_inputs = True
1298
+ return
1299
+
1300
+ self.cache.extend(value.tolist())
1301
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1302
+ if token.strip() != '<|im_end|>':
1303
+ self.response = self.response + token
1304
+ history = self.history + [(self.query, self.response)]
1305
+ self.queue.put((self.response, history))
1306
+ self.cache = []
1307
+ else:
1308
+ self.end()
1309
+
1310
+ def end(self):
1311
+ self.queue.put(None)
1312
+
1313
+ def stream_producer():
1314
+ return self.chat(
1315
+ tokenizer=tokenizer,
1316
+ query=query,
1317
+ streamer=ChatStreamer(tokenizer=tokenizer),
1318
+ history=history,
1319
+ max_new_tokens=max_new_tokens,
1320
+ do_sample=do_sample,
1321
+ temperature=temperature,
1322
+ top_p=top_p,
1323
+ **kwargs,
1324
+ )
1325
+
1326
+ def consumer():
1327
+ producer = threading.Thread(target=stream_producer)
1328
+ producer.start()
1329
+ while True:
1330
+ res = response_queue.get()
1331
+ if res is None:
1332
+ return
1333
+ yield res
1334
+
1335
+ return consumer()
1336
+
1337
+
1338
+ # Copied from transformers.model.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
1339
+ @add_start_docstrings(
1340
+ """
1341
+ The InternLM2 Model transformer with a sequence classification head on top (linear layer).
1342
+
1343
+ [`InternLM2ForSequenceClassification`] uses the last token in order to do the classification,
1344
+ as other causal models (e.g. GPT-2) do.
1345
+
1346
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1347
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1348
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1349
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1350
+ each row of the batch).
1351
+ """,
1352
+ InternLM2_START_DOCSTRING,
1353
+ )
1354
+ class InternLM2VEForSequenceClassification(InternLM2PreTrainedModel):
1355
+ def __init__(self, config):
1356
+ super().__init__(config)
1357
+ self.num_labels = config.num_labels
1358
+ self.model = InternLM2Model(config)
1359
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1360
+
1361
+ # Initialize weights and apply final processing
1362
+ self.post_init()
1363
+
1364
+ def get_input_embeddings(self):
1365
+ return self.model.tok_embeddings
1366
+
1367
+ def set_input_embeddings(self, value):
1368
+ self.model.tok_embeddings = value
1369
+
1370
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1371
+ def forward(
1372
+ self,
1373
+ input_ids: torch.LongTensor = None,
1374
+ attention_mask: Optional[torch.Tensor] = None,
1375
+ position_ids: Optional[torch.LongTensor] = None,
1376
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1377
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1378
+ labels: Optional[torch.LongTensor] = None,
1379
+ use_cache: Optional[bool] = None,
1380
+ output_attentions: Optional[bool] = None,
1381
+ output_hidden_states: Optional[bool] = None,
1382
+ return_dict: Optional[bool] = None,
1383
+ visual_token_mask: Optional[torch.Tensor] = None
1384
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1385
+ r"""
1386
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1387
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1388
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1389
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1390
+ """
1391
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1392
+
1393
+ transformer_outputs = self.model(
1394
+ input_ids,
1395
+ attention_mask=attention_mask,
1396
+ position_ids=position_ids,
1397
+ past_key_values=past_key_values,
1398
+ inputs_embeds=inputs_embeds,
1399
+ use_cache=use_cache,
1400
+ output_attentions=output_attentions,
1401
+ output_hidden_states=output_hidden_states,
1402
+ return_dict=return_dict,
1403
+ visual_token_mask=visual_token_mask
1404
+ )
1405
+ hidden_states = transformer_outputs[0]
1406
+ logits = self.score(hidden_states)
1407
+
1408
+ if input_ids is not None:
1409
+ batch_size = input_ids.shape[0]
1410
+ else:
1411
+ batch_size = inputs_embeds.shape[0]
1412
+
1413
+ if self.config.pad_token_id is None and batch_size != 1:
1414
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1415
+ if self.config.pad_token_id is None:
1416
+ sequence_lengths = -1
1417
+ else:
1418
+ if input_ids is not None:
1419
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1420
+ logits.device
1421
+ )
1422
+ else:
1423
+ sequence_lengths = -1
1424
+
1425
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1426
+
1427
+ loss = None
1428
+ if labels is not None:
1429
+ labels = labels.to(logits.device)
1430
+ if self.config.problem_type is None:
1431
+ if self.num_labels == 1:
1432
+ self.config.problem_type = 'regression'
1433
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1434
+ self.config.problem_type = 'single_label_classification'
1435
+ else:
1436
+ self.config.problem_type = 'multi_label_classification'
1437
+
1438
+ if self.config.problem_type == 'regression':
1439
+ loss_fct = MSELoss()
1440
+ if self.num_labels == 1:
1441
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1442
+ else:
1443
+ loss = loss_fct(pooled_logits, labels)
1444
+ elif self.config.problem_type == 'single_label_classification':
1445
+ loss_fct = CrossEntropyLoss()
1446
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1447
+ elif self.config.problem_type == 'multi_label_classification':
1448
+ loss_fct = BCEWithLogitsLoss()
1449
+ loss = loss_fct(pooled_logits, labels)
1450
+ if not return_dict:
1451
+ output = (pooled_logits,) + transformer_outputs[1:]
1452
+ return ((loss,) + output) if loss is not None else output
1453
+
1454
+ return SequenceClassifierOutputWithPast(
1455
+ loss=loss,
1456
+ logits=pooled_logits,
1457
+ past_key_values=transformer_outputs.past_key_values,
1458
+ hidden_states=transformer_outputs.hidden_states,
1459
+ attentions=transformer_outputs.attentions,
1460
+ )
modeling_internvl_chat.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.distributed as dist
10
+ import torch.utils.checkpoint
11
+ import transformers
12
+ from .conversation import get_conv_template
13
+ from .modeling_internlm2_ve import InternLM2VEForCausalLM
14
+ from peft import LoraConfig, get_peft_model
15
+ from torch import nn
16
+ from torch.nn import CrossEntropyLoss
17
+ from transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,
18
+ LlamaTokenizer, Qwen2ForCausalLM)
19
+ from transformers.modeling_outputs import CausalLMOutputWithPast
20
+ from transformers.modeling_utils import PreTrainedModel
21
+ from transformers.utils import ModelOutput, logging
22
+ import math
23
+ from .configuration_internvl_chat import InternVLChatConfig
24
+ from .modeling_intern_patch import InternVisionPatchModel
25
+ from dataclasses import dataclass
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ def version_cmp(v1, v2, op='eq'):
31
+ import operator
32
+
33
+ from packaging import version
34
+ op_func = getattr(operator, op)
35
+ return op_func(version.parse(v1), version.parse(v2))
36
+
37
+ @dataclass
38
+ class CausalLMOutputWithVisualMask(ModelOutput):
39
+ """
40
+ Base class for causal language model (or autoregressive) outputs.
41
+
42
+ Args:
43
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
44
+ Language modeling loss (for next-token prediction).
45
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
46
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
47
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
48
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
49
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
50
+
51
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
52
+ `past_key_values` input) to speed up sequential decoding.
53
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
54
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
55
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
56
+
57
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
58
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
59
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
60
+ sequence_length)`.
61
+
62
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
63
+ heads.
64
+ """
65
+
66
+ loss: Optional[torch.FloatTensor] = None
67
+ logits: torch.FloatTensor = None
68
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
69
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
70
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
71
+ visual_token_mask : Optional[torch.FloatTensor] = None
72
+
73
+
74
+ class InternVLChatModel(PreTrainedModel):
75
+ config_class = InternVLChatConfig
76
+ main_input_name = 'pixel_values'
77
+ _no_split_modules = ['InternVisionPatchModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer',
78
+ 'Phi3DecoderLayer', 'Qwen2DecoderLayer']
79
+ _supports_flash_attn_2 = True
80
+
81
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
82
+ super().__init__(config)
83
+
84
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
85
+ image_size = config.force_image_size or config.vision_config.image_size
86
+ patch_size = config.vision_config.patch_size
87
+ self.patch_size = patch_size
88
+ self.select_layer = config.select_layer
89
+ self.template = config.template
90
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
91
+ self.downsample_ratio = config.downsample_ratio
92
+ self.ps_version = config.ps_version
93
+ self.llm_arch_name = config.llm_config.architectures[0]
94
+ self.use_visual_token_mask=False
95
+
96
+ logger.info(f'num_image_token: {self.num_image_token}')
97
+ logger.info(f'ps_version: {self.ps_version}')
98
+ if vision_model is not None:
99
+ self.vision_model = vision_model
100
+ else:
101
+ self.vision_model = InternVisionPatchModel(config.vision_config)
102
+
103
+
104
+ if language_model is not None:
105
+ self.language_model = language_model
106
+ else:
107
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
108
+ self.language_model = LlamaForCausalLM(config.llm_config)
109
+ elif config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
110
+ self.language_model = Qwen2ForCausalLM(config.llm_config)
111
+ elif config.llm_config.architectures[0]=='InternLM2VEForCausalLM':
112
+ self.language_model=InternLM2VEForCausalLM(config.llm_config)
113
+ self.use_visual_token_mask=True
114
+ else:
115
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
116
+
117
+ vit_hidden_size = config.vision_config.hidden_size
118
+ llm_hidden_size = config.llm_config.hidden_size
119
+
120
+ self.mlp1 = nn.Sequential(
121
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
122
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
123
+ nn.GELU(),
124
+ nn.Linear(llm_hidden_size, llm_hidden_size)
125
+ )
126
+
127
+ self.img_context_token_id = None
128
+ self.conv_template = get_conv_template(self.template)
129
+ if hasattr(config, 'system_message'):
130
+ self.system_message = config.system_message
131
+ else:
132
+ self.system_message = self.conv_template.system_message
133
+ self.num_samples = 0
134
+
135
+ if config.use_backbone_lora:
136
+ self.wrap_backbone_lora(r=config.use_backbone_lora, lora_alpha=2 * config.use_backbone_lora)
137
+
138
+ if config.use_llm_lora:
139
+ self.wrap_llm_lora(r=config.use_llm_lora, lora_alpha=2 * config.use_llm_lora)
140
+
141
+ def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
142
+ lora_config = LoraConfig(
143
+ r=r,
144
+ target_modules=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'],
145
+ lora_alpha=lora_alpha,
146
+ lora_dropout=lora_dropout,
147
+ )
148
+ self.vision_model = get_peft_model(self.vision_model, lora_config)
149
+ self.vision_model.print_trainable_parameters()
150
+
151
+ def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
152
+ # Determine the target modules based on the architecture of the language model
153
+ if self.llm_arch_name == 'InternLM2ForCausalLM' or self.llm_arch_name == 'InternLM2VEForCausalLM':
154
+ target_modules = ['attention.wqkv', 'attention.wo', 'feed_forward.w1', 'feed_forward.w2', 'feed_forward.w3']
155
+ elif self.llm_arch_name in ['Qwen2ForCausalLM', 'LlamaForCausalLM']:
156
+ target_modules = ['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
157
+ 'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj']
158
+ else:
159
+ raise NotImplemented
160
+ lora_config = LoraConfig(
161
+ r=r,
162
+ target_modules=target_modules,
163
+ lora_alpha=lora_alpha,
164
+ lora_dropout=lora_dropout,
165
+ task_type='CAUSAL_LM'
166
+ )
167
+ self.language_model = get_peft_model(self.language_model, lora_config)
168
+ self.language_model.enable_input_require_grads()
169
+ self.language_model.print_trainable_parameters()
170
+
171
+ def forward(
172
+ self,
173
+ pixel_values: torch.FloatTensor,
174
+ input_ids: torch.LongTensor = None,
175
+ attention_mask: Optional[torch.Tensor] = None,
176
+ position_ids: Optional[torch.LongTensor] = None,
177
+ image_flags: Optional[torch.LongTensor] = None,
178
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
179
+ labels: Optional[torch.LongTensor] = None,
180
+ use_cache: Optional[bool] = None,
181
+ output_attentions: Optional[bool] = None,
182
+ output_hidden_states: Optional[bool] = None,
183
+ return_dict: Optional[bool] = None,
184
+ ) -> Union[Tuple, CausalLMOutputWithVisualMask]:
185
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
186
+
187
+ image_flags = image_flags.squeeze(-1)
188
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
189
+
190
+ vit_embeds = self.extract_feature(pixel_values)
191
+ vit_embeds = vit_embeds[image_flags == 1]
192
+ vit_batch_size = pixel_values.shape[0]
193
+
194
+ B, N, C = input_embeds.shape
195
+ input_embeds = input_embeds.reshape(B * N, C)
196
+
197
+ if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
198
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
199
+
200
+ input_ids = input_ids.reshape(B * N)
201
+ selected = (input_ids == self.img_context_token_id)
202
+ try:
203
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
204
+ ignore_flag = False
205
+ except Exception as e:
206
+ vit_embeds = vit_embeds.reshape(-1, C)
207
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
208
+ f'vit_embeds.shape={vit_embeds.shape}')
209
+ n_token = selected.sum()
210
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
211
+ ignore_flag = True
212
+
213
+ input_embeds = input_embeds.reshape(B, N, C)
214
+
215
+ if self.llm_arch_name=='InternLM2VEForCausalLM':
216
+ visual_token_mask = selected.reshape(B,N,1).to(input_embeds.dtype)
217
+ outputs = self.language_model(
218
+ inputs_embeds=input_embeds,
219
+ attention_mask=attention_mask,
220
+ position_ids=position_ids,
221
+ past_key_values=past_key_values,
222
+ use_cache=use_cache,
223
+ output_attentions=output_attentions,
224
+ output_hidden_states=output_hidden_states,
225
+ return_dict=return_dict,
226
+ visual_token_mask=visual_token_mask
227
+ )
228
+ else:
229
+ outputs = self.language_model(
230
+ inputs_embeds=input_embeds,
231
+ attention_mask=attention_mask,
232
+ position_ids=position_ids,
233
+ past_key_values=past_key_values,
234
+ use_cache=use_cache,
235
+ output_attentions=output_attentions,
236
+ output_hidden_states=output_hidden_states,
237
+ return_dict=return_dict
238
+ )
239
+ logits = outputs.logits
240
+
241
+ loss = None
242
+ if labels is not None:
243
+ # Shift so that tokens < n predict n
244
+ shift_logits = logits[..., :-1, :].contiguous()
245
+ shift_labels = labels[..., 1:].contiguous()
246
+ # Flatten the tokens
247
+ loss_fct = CrossEntropyLoss()
248
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
249
+ shift_labels = shift_labels.view(-1)
250
+ # Enable model parallelism
251
+ shift_labels = shift_labels.to(shift_logits.device)
252
+ loss = loss_fct(shift_logits, shift_labels)
253
+ if ignore_flag:
254
+ loss = loss * 0.0
255
+
256
+ if not return_dict:
257
+ output = (logits,) + outputs[1:]
258
+ return (loss,) + output if loss is not None else output
259
+
260
+ return CausalLMOutputWithPast(
261
+ loss=loss,
262
+ logits=logits,
263
+ past_key_values=outputs.past_key_values,
264
+ hidden_states=outputs.hidden_states,
265
+ attentions=outputs.attentions,
266
+ )
267
+
268
+ def pixel_shuffle(self, x, scale_factor=0.5):
269
+ n, w, h, c = x.size()
270
+ # N, W, H, C --> N, W, H * scale, C // scale
271
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
272
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
273
+ x = x.permute(0, 2, 1, 3).contiguous()
274
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
275
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
276
+ int(c / (scale_factor * scale_factor)))
277
+ if self.ps_version == 'v1':
278
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
279
+ 'which results in a transposed image.')
280
+ else:
281
+ x = x.permute(0, 2, 1, 3).contiguous()
282
+ return x
283
+
284
+ def extract_feature(self, pixel_values):
285
+ if self.select_layer == -1:
286
+ vit_embeds = self.vision_model(
287
+ pixel_values=pixel_values,
288
+ output_hidden_states=False,
289
+ return_dict=True).last_hidden_state
290
+ else:
291
+ vit_embeds = self.vision_model(
292
+ pixel_values=pixel_values,
293
+ output_hidden_states=True,
294
+ return_dict=True).hidden_states[self.select_layer]
295
+
296
+ if int(vit_embeds.shape[1] ** 0.5)**2 != vit_embeds.shape[1]:
297
+ vit_embeds = vit_embeds[:, 1:, :]
298
+
299
+ h = w = int(vit_embeds.shape[1] ** 0.5)
300
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
301
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
302
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
303
+ vit_embeds = self.mlp1(vit_embeds)
304
+ return vit_embeds
305
+
306
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
307
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
308
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
309
+ if history is not None or return_history:
310
+ print('Now multi-turn chat is not supported in batch_chat.')
311
+ raise NotImplementedError
312
+
313
+ if image_counts is not None:
314
+ num_patches_list = image_counts
315
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
316
+
317
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
318
+ self.img_context_token_id = img_context_token_id
319
+
320
+ if verbose and pixel_values is not None:
321
+ image_bs = pixel_values.shape[0]
322
+ print(f'dynamic ViT batch size: {image_bs}')
323
+
324
+ queries = []
325
+ for idx, num_patches in enumerate(num_patches_list):
326
+ question = questions[idx]
327
+ if pixel_values is not None and '<image>' not in question:
328
+ question = '<image>\n' + question
329
+ template = get_conv_template(self.template)
330
+ template.system_message = self.system_message
331
+ template.append_message(template.roles[0], question)
332
+ template.append_message(template.roles[1], None)
333
+ query = template.get_prompt()
334
+
335
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
336
+ query = query.replace('<image>', image_tokens, 1)
337
+ queries.append(query)
338
+
339
+ tokenizer.padding_side = 'left'
340
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
341
+ input_ids = model_inputs['input_ids'].cuda()
342
+ attention_mask = model_inputs['attention_mask'].cuda()
343
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
344
+ generation_config['eos_token_id'] = eos_token_id
345
+ generation_output = self.generate(
346
+ pixel_values=pixel_values,
347
+ input_ids=input_ids,
348
+ attention_mask=attention_mask,
349
+ **generation_config
350
+ )
351
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
352
+ responses = [response.split(template.sep)[0].strip() for response in responses]
353
+ return responses
354
+
355
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
356
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
357
+ verbose=False):
358
+
359
+ if history is None and pixel_values is not None and '<image>' not in question:
360
+ question = '<image>\n' + question
361
+
362
+ if num_patches_list is None:
363
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
364
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
365
+
366
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
367
+ self.img_context_token_id = img_context_token_id
368
+
369
+ template = get_conv_template(self.template)
370
+ template.system_message = self.system_message
371
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
372
+
373
+ history = [] if history is None else history
374
+ for (old_question, old_answer) in history:
375
+ template.append_message(template.roles[0], old_question)
376
+ template.append_message(template.roles[1], old_answer)
377
+ template.append_message(template.roles[0], question)
378
+ template.append_message(template.roles[1], None)
379
+ query = template.get_prompt()
380
+
381
+ if verbose and pixel_values is not None:
382
+ image_bs = pixel_values.shape[0]
383
+ print(f'dynamic ViT batch size: {image_bs}')
384
+
385
+ for num_patches in num_patches_list:
386
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
387
+ query = query.replace('<image>', image_tokens, 1)
388
+
389
+ model_inputs = tokenizer(query, return_tensors='pt')
390
+ input_ids = model_inputs['input_ids'].cuda()
391
+ attention_mask = model_inputs['attention_mask'].cuda()
392
+ generation_config['eos_token_id'] = eos_token_id
393
+ generation_output = self.generate(
394
+ pixel_values=pixel_values,
395
+ input_ids=input_ids,
396
+ attention_mask=attention_mask,
397
+ **generation_config
398
+ )
399
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
400
+ response = response.split(template.sep)[0].strip()
401
+ history.append((question, response))
402
+ if return_history:
403
+ return response, history
404
+ else:
405
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
406
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
407
+ if verbose:
408
+ print(query_to_print, response)
409
+ return response
410
+
411
+ @torch.no_grad()
412
+ def generate(
413
+ self,
414
+ pixel_values: Optional[torch.FloatTensor] = None,
415
+ input_ids: Optional[torch.FloatTensor] = None,
416
+ attention_mask: Optional[torch.LongTensor] = None,
417
+ visual_features: Optional[torch.FloatTensor] = None,
418
+ generation_config: Optional[GenerationConfig] = None,
419
+ output_hidden_states: Optional[bool] = None,
420
+ return_dict: Optional[bool] = None,
421
+ **generate_kwargs,
422
+ ) -> torch.LongTensor:
423
+
424
+ assert self.img_context_token_id is not None
425
+ if pixel_values is not None:
426
+ if visual_features is not None:
427
+ vit_embeds = visual_features
428
+ else:
429
+ vit_embeds = self.extract_feature(pixel_values)
430
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
431
+ B, N, C = input_embeds.shape
432
+ input_embeds = input_embeds.reshape(B * N, C)
433
+
434
+ input_ids = input_ids.reshape(B * N)
435
+ selected = (input_ids == self.img_context_token_id)
436
+ assert selected.sum() != 0
437
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
438
+
439
+ input_embeds = input_embeds.reshape(B, N, C)
440
+ visual_token_mask = selected.reshape(B, N, 1).to(input_embeds.dtype)
441
+ else:
442
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
443
+ B, N, C = input_embeds.shape
444
+ visual_token_mask = torch.zeros_like(input_ids).reshape(B, N, 1).to(input_embeds.dtype)
445
+
446
+ if self.use_visual_token_mask:
447
+ outputs = self.language_model.generate(
448
+ inputs_embeds=input_embeds,
449
+ attention_mask=attention_mask,
450
+ generation_config=generation_config,
451
+ output_hidden_states=output_hidden_states,
452
+ return_dict=return_dict,
453
+ use_cache=True,
454
+ visual_token_mask=visual_token_mask,
455
+ **generate_kwargs,
456
+ )
457
+ else:
458
+ outputs = self.language_model.generate(
459
+ inputs_embeds=input_embeds,
460
+ attention_mask=attention_mask,
461
+ generation_config=generation_config,
462
+ output_hidden_states=output_hidden_states,
463
+ return_dict=return_dict,
464
+ use_cache=True,
465
+ **generate_kwargs,
466
+ )
467
+
468
+ return outputs
special_tokens_map.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|action_start|>",
6
+ "<|action_end|>",
7
+ "<|interpreter|>",
8
+ "<|plugin|>",
9
+ "<img>",
10
+ "</img>",
11
+ "<IMG_CONTEXT>",
12
+ "<quad>",
13
+ "</quad>",
14
+ "<ref>",
15
+ "</ref>",
16
+ "<box>",
17
+ "</box>"
18
+ ],
19
+ "bos_token": {
20
+ "content": "<s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "eos_token": {
27
+ "content": "</s>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ },
33
+ "pad_token": {
34
+ "content": "</s>",
35
+ "lstrip": false,
36
+ "normalized": false,
37
+ "rstrip": false,
38
+ "single_word": false
39
+ },
40
+ "unk_token": {
41
+ "content": "<unk>",
42
+ "lstrip": false,
43
+ "normalized": false,
44
+ "rstrip": false,
45
+ "single_word": false
46
+ }
47
+ }
tokenization_internlm2.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """Tokenization classes for InternLM."""
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ import sentencepiece as spm
23
+ from transformers.tokenization_utils import PreTrainedTokenizer
24
+ from transformers.utils import logging
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
29
+
30
+ PRETRAINED_VOCAB_FILES_MAP = {}
31
+
32
+
33
+ # Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
34
+ class InternLM2Tokenizer(PreTrainedTokenizer):
35
+ """
36
+ Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
37
+
38
+ Args:
39
+ vocab_file (`str`):
40
+ Path to the vocabulary file.
41
+ """
42
+
43
+ vocab_files_names = VOCAB_FILES_NAMES
44
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
45
+ model_input_names = ['input_ids', 'attention_mask']
46
+ _auto_class = 'AutoTokenizer'
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file,
51
+ unk_token='<unk>',
52
+ bos_token='<s>',
53
+ eos_token='</s>',
54
+ pad_token='</s>',
55
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
56
+ add_bos_token=True,
57
+ add_eos_token=False,
58
+ decode_with_prefix_space=False,
59
+ clean_up_tokenization_spaces=False,
60
+ **kwargs,
61
+ ):
62
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
63
+ self.vocab_file = vocab_file
64
+ self.add_bos_token = add_bos_token
65
+ self.add_eos_token = add_eos_token
66
+ self.decode_with_prefix_space = decode_with_prefix_space
67
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
68
+ self.sp_model.Load(vocab_file)
69
+ self._no_prefix_space_tokens = None
70
+ super().__init__(
71
+ bos_token=bos_token,
72
+ eos_token=eos_token,
73
+ unk_token=unk_token,
74
+ pad_token=pad_token,
75
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
76
+ **kwargs,
77
+ )
78
+
79
+ @property
80
+ def no_prefix_space_tokens(self):
81
+ if self._no_prefix_space_tokens is None:
82
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
83
+ self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith('▁')}
84
+ return self._no_prefix_space_tokens
85
+
86
+ @property
87
+ def vocab_size(self):
88
+ """Returns vocab size"""
89
+ return self.sp_model.get_piece_size()
90
+
91
+ @property
92
+ def bos_token_id(self) -> Optional[int]:
93
+ return self.sp_model.bos_id()
94
+
95
+ @property
96
+ def eos_token_id(self) -> Optional[int]:
97
+ return self.sp_model.eos_id()
98
+
99
+ def get_vocab(self):
100
+ """Returns vocab as a dict"""
101
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
102
+ vocab.update(self.added_tokens_encoder)
103
+ return vocab
104
+
105
+ def _tokenize(self, text):
106
+ """Returns a tokenized string."""
107
+ return self.sp_model.encode(text, out_type=str)
108
+
109
+ def _convert_token_to_id(self, token):
110
+ """Converts a token (str) in an id using the vocab."""
111
+ return self.sp_model.piece_to_id(token)
112
+
113
+ def _convert_id_to_token(self, index):
114
+ """Converts an index (integer) in a token (str) using the vocab."""
115
+ token = self.sp_model.IdToPiece(index)
116
+ return token
117
+
118
+ def _maybe_add_prefix_space(self, tokens, decoded):
119
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
120
+ return ' ' + decoded
121
+ else:
122
+ return decoded
123
+
124
+ def convert_tokens_to_string(self, tokens):
125
+ """Converts a sequence of tokens (string) in a single string."""
126
+ current_sub_tokens = []
127
+ out_string = ''
128
+ prev_is_special = False
129
+ for token in tokens:
130
+ # make sure that special tokens are not decoded using sentencepiece model
131
+ if token in self.all_special_tokens:
132
+ if not prev_is_special:
133
+ out_string += ' '
134
+ out_string += self.sp_model.decode(current_sub_tokens) + token
135
+ prev_is_special = True
136
+ current_sub_tokens = []
137
+ else:
138
+ current_sub_tokens.append(token)
139
+ prev_is_special = False
140
+ out_string += self.sp_model.decode(current_sub_tokens)
141
+ out_string = self.clean_up_tokenization(out_string)
142
+ out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
143
+ return out_string[1:]
144
+
145
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
146
+ """
147
+ Save the vocabulary and special tokens file to a directory.
148
+
149
+ Args:
150
+ save_directory (`str`):
151
+ The directory in which to save the vocabulary.
152
+
153
+ Returns:
154
+ `Tuple(str)`: Paths to the files saved.
155
+ """
156
+ if not os.path.isdir(save_directory):
157
+ logger.error(f'Vocabulary path ({save_directory}) should be a directory')
158
+ return
159
+ out_vocab_file = os.path.join(
160
+ save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']
161
+ )
162
+
163
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
164
+ copyfile(self.vocab_file, out_vocab_file)
165
+ elif not os.path.isfile(self.vocab_file):
166
+ with open(out_vocab_file, 'wb') as fi:
167
+ content_spiece_model = self.sp_model.serialized_model_proto()
168
+ fi.write(content_spiece_model)
169
+
170
+ return (out_vocab_file,)
171
+
172
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
173
+ if self.add_bos_token:
174
+ bos_token_ids = [self.bos_token_id]
175
+ else:
176
+ bos_token_ids = []
177
+
178
+ output = bos_token_ids + token_ids_0
179
+
180
+ if token_ids_1 is not None:
181
+ output = output + token_ids_1
182
+
183
+ if self.add_eos_token:
184
+ output = output + [self.eos_token_id]
185
+
186
+ return output
187
+
188
+ def get_special_tokens_mask(
189
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
190
+ ) -> List[int]:
191
+ """
192
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
193
+ special tokens using the tokenizer `prepare_for_model` method.
194
+
195
+ Args:
196
+ token_ids_0 (`List[int]`):
197
+ List of IDs.
198
+ token_ids_1 (`List[int]`, *optional*):
199
+ Optional second list of IDs for sequence pairs.
200
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
201
+ Whether or not the token list is already formatted with special tokens for the model.
202
+
203
+ Returns:
204
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
205
+ """
206
+ if already_has_special_tokens:
207
+ return super().get_special_tokens_mask(
208
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
209
+ )
210
+
211
+ if token_ids_1 is None:
212
+ return [1] + ([0] * len(token_ids_0)) + [1]
213
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
214
+
215
+ def create_token_type_ids_from_sequences(
216
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
217
+ ) -> List[int]:
218
+ """
219
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
220
+ use of token type ids, therefore a list of zeros is returned.
221
+
222
+ Args:
223
+ token_ids_0 (`List[int]`):
224
+ List of IDs.
225
+ token_ids_1 (`List[int]`, *optional*):
226
+ Optional second list of IDs for sequence pairs.
227
+
228
+ Returns:
229
+ `List[int]`: List of zeros.
230
+ """
231
+ eos = [self.eos_token_id]
232
+
233
+ if token_ids_1 is None:
234
+ return len(token_ids_0 + eos) * [0]
235
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
tokenization_internlm2_fast.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """Tokenization Fast class for InternLM."""
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, Optional, Tuple
21
+
22
+ from tokenizers import Tokenizer, decoders, normalizers, processors
23
+ from tokenizers.models import BPE
24
+ from transformers.convert_slow_tokenizer import (SLOW_TO_FAST_CONVERTERS,
25
+ SentencePieceExtractor,
26
+ SpmConverter)
27
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
28
+ from transformers.utils import logging
29
+
30
+ from .tokenization_internlm2 import InternLM2Tokenizer
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
35
+
36
+
37
+ # Modified from transformers.convert_slow_tokenizer.LlamaConverter
38
+ class InternLM2Converter(SpmConverter):
39
+ handle_byte_fallback = True
40
+
41
+ def vocab(self, proto):
42
+ vocab = [
43
+ ('<unk>', 0.0),
44
+ ('<s>', 0.0),
45
+ ('</s>', 0.0),
46
+ ]
47
+ vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
48
+ return vocab
49
+
50
+ def unk_id(self, proto):
51
+ unk_id = 0
52
+ return unk_id
53
+
54
+ def decoder(self, replacement, add_prefix_space):
55
+ return decoders.Sequence(
56
+ [
57
+ decoders.Replace('▁', ' '),
58
+ decoders.ByteFallback(),
59
+ decoders.Fuse(),
60
+ decoders.Strip(content=' ', left=1),
61
+ ]
62
+ )
63
+
64
+ def tokenizer(self, proto):
65
+ model_type = proto.trainer_spec.model_type
66
+ vocab_scores = self.vocab(proto)
67
+ # special tokens
68
+ added_tokens = self.original_tokenizer.added_tokens_decoder
69
+ for i in range(len(vocab_scores)):
70
+ piece, score = vocab_scores[i]
71
+ if i in added_tokens:
72
+ vocab_scores[i] = (added_tokens[i].content, score)
73
+ if model_type == 1:
74
+ raise RuntimeError('InternLM2 is supposed to be a BPE model!')
75
+
76
+ elif model_type == 2:
77
+ _, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
78
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
79
+ tokenizer = Tokenizer(
80
+ BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True)
81
+ )
82
+ tokenizer.add_special_tokens(
83
+ [ added_token for index, added_token in added_tokens.items()]
84
+ )
85
+ else:
86
+ raise Exception(
87
+ "You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
88
+ )
89
+
90
+ return tokenizer
91
+
92
+ def normalizer(self, proto):
93
+ normalizers_list = []
94
+ if proto.normalizer_spec.add_dummy_prefix:
95
+ normalizers_list.append(normalizers.Prepend(prepend='▁'))
96
+ normalizers_list.append(normalizers.Replace(pattern=' ', content='▁'))
97
+ return normalizers.Sequence(normalizers_list)
98
+
99
+ def pre_tokenizer(self, replacement, add_prefix_space):
100
+ return None
101
+
102
+
103
+ SLOW_TO_FAST_CONVERTERS['InternLM2Tokenizer'] = InternLM2Converter
104
+
105
+
106
+ # Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFast
107
+ class InternLM2TokenizerFast(PreTrainedTokenizerFast):
108
+ vocab_files_names = VOCAB_FILES_NAMES
109
+ slow_tokenizer_class = InternLM2Tokenizer
110
+ padding_side = 'left'
111
+ model_input_names = ['input_ids', 'attention_mask']
112
+ _auto_class = 'AutoTokenizer'
113
+
114
+ def __init__(
115
+ self,
116
+ vocab_file,
117
+ unk_token='<unk>',
118
+ bos_token='<s>',
119
+ eos_token='</s>',
120
+ pad_token='</s>',
121
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
122
+ add_bos_token=True,
123
+ add_eos_token=False,
124
+ decode_with_prefix_space=False,
125
+ clean_up_tokenization_spaces=False,
126
+ **kwargs,
127
+ ):
128
+ super().__init__(
129
+ vocab_file=vocab_file,
130
+ unk_token=unk_token,
131
+ bos_token=bos_token,
132
+ eos_token=eos_token,
133
+ pad_token=pad_token,
134
+ sp_model_kwargs=sp_model_kwargs,
135
+ add_bos_token=add_bos_token,
136
+ add_eos_token=add_eos_token,
137
+ decode_with_prefix_space=decode_with_prefix_space,
138
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
139
+ **kwargs,
140
+ )
141
+ self._add_bos_token = add_bos_token
142
+ self._add_eos_token = add_eos_token
143
+ self.update_post_processor()
144
+ self.vocab_file = vocab_file
145
+
146
+ @property
147
+ def can_save_slow_tokenizer(self) -> bool:
148
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
149
+
150
+ def update_post_processor(self):
151
+ """
152
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
153
+ """
154
+ bos = self.bos_token
155
+ bos_token_id = self.bos_token_id
156
+ if bos is None and self.add_bos_token:
157
+ raise ValueError('add_bos_token = True but bos_token = None')
158
+
159
+ eos = self.eos_token
160
+ eos_token_id = self.eos_token_id
161
+ if eos is None and self.add_eos_token:
162
+ raise ValueError('add_eos_token = True but eos_token = None')
163
+
164
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
165
+ pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
166
+
167
+ special_tokens = []
168
+ if self.add_bos_token:
169
+ special_tokens.append((bos, bos_token_id))
170
+ if self.add_eos_token:
171
+ special_tokens.append((eos, eos_token_id))
172
+ self._tokenizer.post_processor = processors.TemplateProcessing(
173
+ single=single, pair=pair, special_tokens=special_tokens
174
+ )
175
+
176
+ @property
177
+ def add_eos_token(self):
178
+ return self._add_eos_token
179
+
180
+ @property
181
+ def add_bos_token(self):
182
+ return self._add_bos_token
183
+
184
+ @add_eos_token.setter
185
+ def add_eos_token(self, value):
186
+ self._add_eos_token = value
187
+ self.update_post_processor()
188
+
189
+ @add_bos_token.setter
190
+ def add_bos_token(self, value):
191
+ self._add_bos_token = value
192
+ self.update_post_processor()
193
+
194
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
195
+ if not self.can_save_slow_tokenizer:
196
+ raise ValueError(
197
+ 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
198
+ 'tokenizer.'
199
+ )
200
+
201
+ if not os.path.isdir(save_directory):
202
+ logger.error(f'Vocabulary path ({save_directory}) should be a directory')
203
+ return
204
+ out_vocab_file = os.path.join(
205
+ save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']
206
+ )
207
+
208
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
209
+ copyfile(self.vocab_file, out_vocab_file)
210
+
211
+ return (out_vocab_file,)
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
3
+ size 1477754
tokenizer_config.json ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<unk>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "92538": {
28
+ "content": "<|plugin|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "92539": {
36
+ "content": "<|interpreter|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "92540": {
44
+ "content": "<|action_end|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "92541": {
52
+ "content": "<|action_start|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "92542": {
60
+ "content": "<|im_end|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "92543": {
68
+ "content": "<|im_start|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "92544": {
76
+ "content": "<img>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "92545": {
84
+ "content": "</img>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "92546": {
92
+ "content": "<IMG_CONTEXT>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "92547": {
100
+ "content": "<quad>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "92548": {
108
+ "content": "</quad>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "92549": {
116
+ "content": "<ref>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "92550": {
124
+ "content": "</ref>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "92551": {
132
+ "content": "<box>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "92552": {
140
+ "content": "</box>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ }
147
+ },
148
+ "additional_special_tokens": [
149
+ "<|im_start|>",
150
+ "<|im_end|>",
151
+ "<|action_start|>",
152
+ "<|action_end|>",
153
+ "<|interpreter|>",
154
+ "<|plugin|>",
155
+ "<img>",
156
+ "</img>",
157
+ "<IMG_CONTEXT>",
158
+ "<quad>",
159
+ "</quad>",
160
+ "<ref>",
161
+ "</ref>",
162
+ "<box>",
163
+ "</box>"
164
+ ],
165
+ "auto_map": {
166
+ "AutoTokenizer": [
167
+ "tokenization_internlm2.InternLM2Tokenizer",
168
+ null
169
+ ]
170
+ },
171
+ "bos_token": "<s>",
172
+ "chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
173
+ "clean_up_tokenization_spaces": false,
174
+ "eos_token": "</s>",
175
+ "model_max_length": 8192,
176
+ "pad_token": "</s>",
177
+ "tokenizer_class": "InternLM2Tokenizer",
178
+ "unk_token": "<unk>"
179
+ }