HongyuanTao commited on
Commit
5118ddd
·
verified ·
1 Parent(s): 1a16b1c

Upload 18 files

Browse files
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,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "_name_or_path": "hustvl/mmMamba_hybrid",
4
+ "architectures": [
5
+ "mmMambaChatModel"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_mmMamba_chat.mmMambaChatConfig",
9
+ "AutoModel": "modeling_mmMamba_chat.mmMambaChatModel",
10
+ "AutoModelForCausalLM": "modeling_mmMamba_chat.mmMambaChatModel"
11
+ },
12
+ "downsample_ratio": 0.5,
13
+ "dynamic_image_size": true,
14
+ "embedding_config": {
15
+ "_name_or_path": "",
16
+ "add_cross_attention": false,
17
+ "architectures": null,
18
+ "attention_bias": false,
19
+ "attention_dropout": 0.0,
20
+ "attn_implementation": "flash_attention_2",
21
+ "bad_words_ids": null,
22
+ "begin_suppress_tokens": null,
23
+ "bos_token_id": null,
24
+ "chunk_size_feed_forward": 0,
25
+ "cross_attention_hidden_size": null,
26
+ "decoder_start_token_id": null,
27
+ "diversity_penalty": 0.0,
28
+ "do_sample": false,
29
+ "downsample_ratio": 0.5,
30
+ "drop_path_rate": 0.0,
31
+ "dropout": 0.0,
32
+ "early_stopping": false,
33
+ "encoder_no_repeat_ngram_size": 0,
34
+ "eos_token_id": null,
35
+ "exponential_decay_length_penalty": null,
36
+ "finetuning_task": null,
37
+ "forced_bos_token_id": null,
38
+ "forced_eos_token_id": null,
39
+ "hidden_act": "silu",
40
+ "hidden_size": 2048,
41
+ "id2label": {
42
+ "0": "LABEL_0",
43
+ "1": "LABEL_1"
44
+ },
45
+ "image_size": 448,
46
+ "img_context_token_id": 92546,
47
+ "initializer_factor": 1e-05,
48
+ "initializer_range": 0.02,
49
+ "intermediate_size": 8192,
50
+ "is_decoder": false,
51
+ "is_encoder_decoder": false,
52
+ "label2id": {
53
+ "LABEL_0": 0,
54
+ "LABEL_1": 1
55
+ },
56
+ "layers_block_type":["mha", "mamba2", "mamba2", "mamba2", "mha", "mamba2", "mamba2", "mamba2"],
57
+ "layer_norm_eps": 1e-06,
58
+ "length_penalty": 1.0,
59
+ "llm_hidden_size": 2048,
60
+ "llm_vocab_size": 92553,
61
+ "max_length": 20,
62
+ "max_position_embeddings": 32768,
63
+ "min_length": 0,
64
+ "mlp_bias": false,
65
+ "model_type": "mmMamba_embedding",
66
+ "no_repeat_ngram_size": 0,
67
+ "norm_type": "rms_norm",
68
+ "num_attention_heads": 16,
69
+ "num_beam_groups": 1,
70
+ "num_beams": 1,
71
+ "num_channels": 3,
72
+ "num_hidden_layers": 8,
73
+ "num_key_value_heads": 8,
74
+ "num_return_sequences": 1,
75
+ "output_attentions": false,
76
+ "output_hidden_states": false,
77
+ "output_scores": false,
78
+ "pad_token_id": null,
79
+ "patch_size": 14,
80
+ "pixel_shuffle_loc": "pre",
81
+ "prefix": null,
82
+ "pretraining_tp": 1,
83
+ "problem_type": null,
84
+ "pruned_heads": {},
85
+ "qk_normalization": true,
86
+ "qkv_bias": false,
87
+ "remove_invalid_values": false,
88
+ "repetition_penalty": 1.0,
89
+ "return_dict": true,
90
+ "return_dict_in_generate": false,
91
+ "rms_norm_eps": 1e-05,
92
+ "rope_scaling": null,
93
+ "rope_theta": 1000000.0,
94
+ "sep_token_id": null,
95
+ "special_token_maps": {},
96
+ "suppress_tokens": null,
97
+ "target_hidden_size": 2048,
98
+ "task_specific_params": null,
99
+ "temperature": 1.0,
100
+ "tf_legacy_loss": false,
101
+ "tie_encoder_decoder": false,
102
+ "tie_word_embeddings": true,
103
+ "tokenizer_class": null,
104
+ "top_k": 50,
105
+ "top_p": 1.0,
106
+ "torch_dtype": null,
107
+ "torchscript": false,
108
+ "transformers_version": "4.43.1",
109
+ "typical_p": 1.0,
110
+ "use_autoregressive_loss": false,
111
+ "use_bfloat16": false,
112
+ "use_flash_attn": true,
113
+ "use_img_start_end_tokens": true,
114
+ "use_ls": false,
115
+ "use_pixel_shuffle_proj": true
116
+ },
117
+ "force_image_size": 448,
118
+ "llm_config": {
119
+ "_name_or_path": "",
120
+ "add_cross_attention": false,
121
+ "architectures": [
122
+ "mmMambaForCausalLM"
123
+ ],
124
+ "attn_implementation": "flash_attention_2",
125
+ "auto_map": {
126
+ "AutoConfig": "configuration_mmMamba.mmMambaConfig",
127
+ "AutoModel": "modeling_mmMamba.mmMambaForCausalLM",
128
+ "AutoModelForCausalLM": "modeling_mmMamba.mmMambaForCausalLM"
129
+ },
130
+ "bad_words_ids": null,
131
+ "begin_suppress_tokens": null,
132
+ "bias": false,
133
+ "bos_token_id": 1,
134
+ "chunk_size_feed_forward": 0,
135
+ "cross_attention_hidden_size": null,
136
+ "decoder_start_token_id": null,
137
+ "diversity_penalty": 0.0,
138
+ "do_sample": false,
139
+ "early_stopping": false,
140
+ "encoder_no_repeat_ngram_size": 0,
141
+ "eos_token_id": 2,
142
+ "exponential_decay_length_penalty": null,
143
+ "finetuning_task": null,
144
+ "forced_bos_token_id": null,
145
+ "forced_eos_token_id": null,
146
+ "hidden_act": "silu",
147
+ "hidden_size": 2048,
148
+ "id2label": {
149
+ "0": "LABEL_0",
150
+ "1": "LABEL_1"
151
+ },
152
+ "initializer_range": 0.02,
153
+ "intermediate_size": 8192,
154
+ "is_decoder": false,
155
+ "is_encoder_decoder": false,
156
+ "label2id": {
157
+ "LABEL_0": 0,
158
+ "LABEL_1": 1
159
+ },
160
+ "layers_block_type":[
161
+ "mha", "mamba2", "mamba2", "mamba2", "mha", "mamba2", "mamba2", "mamba2",
162
+ "mha", "mamba2", "mamba2", "mamba2", "mha", "mamba2", "mamba2", "mamba2",
163
+ "mha", "mamba2", "mamba2", "mamba2", "mha", "mamba2", "mamba2", "mamba2"
164
+ ],
165
+ "length_penalty": 1.0,
166
+ "max_length": 20,
167
+ "max_position_embeddings": 32768,
168
+ "min_length": 0,
169
+ "model_type": "mmMamba",
170
+ "no_repeat_ngram_size": 0,
171
+ "num_attention_heads": 16,
172
+ "num_beam_groups": 1,
173
+ "num_beams": 1,
174
+ "num_hidden_layers": 24,
175
+ "num_key_value_heads": 8,
176
+ "num_return_sequences": 1,
177
+ "output_attentions": false,
178
+ "output_hidden_states": false,
179
+ "output_scores": false,
180
+ "pad_token_id": 2,
181
+ "prefix": null,
182
+ "problem_type": null,
183
+ "pruned_heads": {},
184
+ "remove_invalid_values": false,
185
+ "repetition_penalty": 1.0,
186
+ "return_dict": true,
187
+ "return_dict_in_generate": false,
188
+ "rms_norm_eps": 1e-05,
189
+ "rope_scaling": {
190
+ "factor": 2.0,
191
+ "type": "dynamic"
192
+ },
193
+ "rope_theta": 1000000,
194
+ "sep_token_id": null,
195
+ "suppress_tokens": null,
196
+ "task_specific_params": null,
197
+ "temperature": 1.0,
198
+ "tf_legacy_loss": false,
199
+ "tie_encoder_decoder": false,
200
+ "tie_word_embeddings": false,
201
+ "tokenizer_class": null,
202
+ "top_k": 50,
203
+ "top_p": 1.0,
204
+ "torch_dtype": "bfloat16",
205
+ "torchscript": false,
206
+ "transformers_version": "4.43.1",
207
+ "typical_p": 1.0,
208
+ "use_bfloat16": true,
209
+ "use_cache": false,
210
+ "vocab_size": 92553,
211
+
212
+ "feature_map": "softmax_dim",
213
+ "feature_map_kwargs": {
214
+ "eps": 1e-12,
215
+ "fullspace": true
216
+ },
217
+ "learned_kernel": "untied_head_einsum",
218
+ "learned_kernel_kwargs":{
219
+ "feature_dim": 64,
220
+ "skip_connection": false,
221
+ "bias": false,
222
+ "zero_init": false
223
+ },
224
+ "tie_qk_kernels": false
225
+ },
226
+ "max_dynamic_patch": 12,
227
+ "min_dynamic_patch": 1,
228
+ "model_type": "mmMamba_chat",
229
+ "normalize_encoder_output": true,
230
+ "pad2square": false,
231
+ "ps_version": "v2",
232
+ "select_layer": -1,
233
+ "template": "internlm2-chat",
234
+ "torch_dtype": "bfloat16",
235
+ "transformers_version": null,
236
+ "use_backbone_lora": 0,
237
+ "use_llm_lora": 0,
238
+ "use_mlp": false,
239
+ "use_thumbnail": true
240
+ }
configuration_mmMamba.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The mmMamba 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
+ """ mmMamba 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
+ mmMamba_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
24
+
25
+
26
+ class mmMambaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`mmMambaModel`]. It is used to instantiate
29
+ a mmMamba model according to the specified arguments, defining the model architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32000):
37
+ Vocabulary size of the mmMamba model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`mmMambaModel`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 11008):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
54
+ `num_attention_heads`.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
58
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
59
+ just in case (e.g., 512 or 1024 or 2048).
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
68
+ Whether to tie weight embeddings
69
+ Example:
70
+
71
+ """
72
+ model_type = 'mmMamba'
73
+ _auto_class = 'AutoConfig'
74
+
75
+ def __init__( # pylint: disable=W0102
76
+ self,
77
+ vocab_size=103168,
78
+ hidden_size=4096,
79
+ intermediate_size=11008,
80
+ num_hidden_layers=32,
81
+ num_attention_heads=32,
82
+ num_key_value_heads=None,
83
+ hidden_act='silu',
84
+ max_position_embeddings=2048,
85
+ initializer_range=0.02,
86
+ rms_norm_eps=1e-6,
87
+ use_cache=True,
88
+ pad_token_id=0,
89
+ bos_token_id=1,
90
+ eos_token_id=2,
91
+ tie_word_embeddings=False,
92
+ bias=True,
93
+ rope_theta=10000,
94
+ rope_scaling=None,
95
+ attn_implementation='eager',
96
+ tie_qk_kernels=None,
97
+ layers_block_type = ["mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2",
98
+ "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2",
99
+ "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2"],
100
+ **kwargs,
101
+ ):
102
+ self.vocab_size = vocab_size
103
+ self.max_position_embeddings = max_position_embeddings
104
+ self.hidden_size = hidden_size
105
+ self.intermediate_size = intermediate_size
106
+ self.num_hidden_layers = num_hidden_layers
107
+ self.num_attention_heads = num_attention_heads
108
+ self.bias = bias
109
+
110
+ if num_key_value_heads is None:
111
+ num_key_value_heads = num_attention_heads
112
+ self.num_key_value_heads = num_key_value_heads
113
+
114
+ self.hidden_act = hidden_act
115
+ self.initializer_range = initializer_range
116
+ self.rms_norm_eps = rms_norm_eps
117
+ self.use_cache = use_cache
118
+ self.rope_theta = rope_theta
119
+ self.rope_scaling = rope_scaling
120
+ self._rope_scaling_validation()
121
+
122
+ self.tie_qk_kernels = tie_qk_kernels
123
+ self.layers_block_type = layers_block_type
124
+
125
+ self.attn_implementation = attn_implementation
126
+ if self.attn_implementation is None:
127
+ self.attn_implementation = 'eager'
128
+ super().__init__(
129
+ pad_token_id=pad_token_id,
130
+ bos_token_id=bos_token_id,
131
+ eos_token_id=eos_token_id,
132
+ tie_word_embeddings=tie_word_embeddings,
133
+ **kwargs,
134
+ )
135
+
136
+ def _rope_scaling_validation(self):
137
+ """
138
+ Validate the `rope_scaling` configuration.
139
+ """
140
+ if self.rope_scaling is None:
141
+ return
142
+
143
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
144
+ raise ValueError(
145
+ '`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
146
+ f'got {self.rope_scaling}'
147
+ )
148
+ rope_scaling_type = self.rope_scaling.get('type', None)
149
+ rope_scaling_factor = self.rope_scaling.get('factor', None)
150
+ if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
151
+ raise ValueError(
152
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
153
+ )
154
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
155
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
156
+
configuration_mmMamba_chat.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+ from .configuration_mmMamba import mmMambaConfig
4
+ from transformers.configuration_utils import PretrainedConfig
5
+ from transformers.utils import logging
6
+
7
+ from .configuration_mmMamba_embedding import mmMambaEmbeddingConfig
8
+
9
+ logger = logging.get_logger(__name__)
10
+
11
+
12
+ class mmMambaChatConfig(PretrainedConfig):
13
+ model_type = 'mmMamba_chat'
14
+ is_composition = True
15
+
16
+ def __init__(
17
+ self,
18
+ embedding_config=None,
19
+ llm_config=None,
20
+ use_backbone_lora=0,
21
+ use_llm_lora=0,
22
+ pad2square=False,
23
+ select_layer=-1,
24
+ force_image_size=None,
25
+ downsample_ratio=0.5,
26
+ template=None,
27
+ dynamic_image_size=False,
28
+ use_thumbnail=False,
29
+ ps_version='v1',
30
+ min_dynamic_patch=1,
31
+ max_dynamic_patch=6,
32
+ normalize_encoder_output=False,
33
+ **kwargs):
34
+ super().__init__(**kwargs)
35
+
36
+ if embedding_config is None:
37
+ embedding_config = {}
38
+ logger.info('embedding_config is None. Initializing the VisionConfig with default values.')
39
+
40
+ if llm_config is None:
41
+ llm_config = {}
42
+ logger.info('llm_config is None. Initializing the Config config with default values (`Config`).')
43
+
44
+ self.embedding_config = mmMambaEmbeddingConfig(**embedding_config)
45
+ self.llm_config = mmMambaConfig(**llm_config)
46
+
47
+ self.use_backbone_lora = use_backbone_lora
48
+ self.use_llm_lora = use_llm_lora
49
+ self.pad2square = pad2square
50
+ self.select_layer = select_layer
51
+ self.force_image_size = force_image_size
52
+ self.downsample_ratio = downsample_ratio
53
+ self.template = template
54
+ self.dynamic_image_size = dynamic_image_size
55
+ self.use_thumbnail = use_thumbnail
56
+ self.ps_version = ps_version # pixel shuffle version
57
+ self.min_dynamic_patch = min_dynamic_patch
58
+ self.max_dynamic_patch = max_dynamic_patch
59
+ self.normalize_encoder_output = normalize_encoder_output
60
+
61
+ logger.info(f'vision_select_layer: {self.select_layer}')
62
+ logger.info(f'ps_version: {self.ps_version}')
63
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
64
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
65
+
66
+ def to_dict(self):
67
+ """
68
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
69
+
70
+ Returns:
71
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
72
+ """
73
+ output = copy.deepcopy(self.__dict__)
74
+ output['embedding_config'] = self.embedding_config.to_dict()
75
+ output['llm_config'] = self.llm_config.to_dict()
76
+ output['model_type'] = self.__class__.model_type
77
+ output['use_backbone_lora'] = self.use_backbone_lora
78
+ output['use_llm_lora'] = self.use_llm_lora
79
+ output['pad2square'] = self.pad2square
80
+ output['select_layer'] = self.select_layer
81
+ output['force_image_size'] = self.force_image_size
82
+ output['downsample_ratio'] = self.downsample_ratio
83
+ output['template'] = self.template
84
+ output['dynamic_image_size'] = self.dynamic_image_size
85
+ output['use_thumbnail'] = self.use_thumbnail
86
+ output['ps_version'] = self.ps_version
87
+ output['min_dynamic_patch'] = self.min_dynamic_patch
88
+ output['max_dynamic_patch'] = self.max_dynamic_patch
89
+ output['normalize_encoder_output'] = self.normalize_encoder_output
90
+
91
+ return output
92
+
93
+
configuration_mmMamba_embedding.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Union
3
+ import json
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+
11
+ class mmMambaEmbeddingConfig(PretrainedConfig):
12
+
13
+ model_type = 'mmMamba_embedding'
14
+
15
+ def __init__(
16
+ self,
17
+ num_hidden_layers=32,
18
+ initializer_factor=1e-5,
19
+ use_autoregressive_loss=False,
20
+ # vision embedding
21
+ num_channels=3,
22
+ patch_size=14,
23
+ image_size=224,
24
+ # attention layer
25
+ hidden_size=4096,
26
+ num_attention_heads=32,
27
+ num_key_value_heads=32,
28
+ attention_bias=False,
29
+ attention_dropout=0.0,
30
+ max_position_embeddings=4096,
31
+ rope_theta=10000.0,
32
+ rope_scaling=None,
33
+ # mlp layer
34
+ intermediate_size=11008,
35
+ mlp_bias=False,
36
+ hidden_act='silu',
37
+ # rms norm
38
+ rms_norm_eps=1e-5,
39
+ # pretraining
40
+ pretraining_tp=1,
41
+ use_ls=True,
42
+ use_img_start_end_tokens=True,
43
+ special_token_maps={},
44
+ llm_vocab_size=92553,
45
+ llm_hidden_size=2048,
46
+ attn_implementation='flash_attention_2',
47
+ downsample_ratio=0.5,
48
+ img_context_token_id=92546,
49
+ pixel_shuffle_loc="pre",
50
+ layers_block_type = ["mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2"],
51
+ **kwargs,
52
+ ):
53
+ super().__init__(**kwargs)
54
+
55
+ self.num_hidden_layers = num_hidden_layers
56
+ self.initializer_factor = initializer_factor
57
+ self.use_autoregressive_loss = use_autoregressive_loss
58
+
59
+ self.num_channels = num_channels
60
+ self.patch_size = patch_size
61
+ self.image_size = image_size
62
+
63
+ self.hidden_size = hidden_size
64
+ self.num_attention_heads = num_attention_heads
65
+ self.num_key_value_heads = num_key_value_heads
66
+ self.attention_bias = attention_bias
67
+ self.attention_dropout = attention_dropout
68
+ self.max_position_embeddings = max_position_embeddings
69
+ self.rope_theta = rope_theta
70
+ self.rope_scaling = rope_scaling
71
+
72
+ self.intermediate_size = intermediate_size
73
+ self.layers_block_type = layers_block_type
74
+ self.mlp_bias = mlp_bias
75
+ self.hidden_act = hidden_act
76
+
77
+ self.rms_norm_eps = rms_norm_eps
78
+
79
+ self.pretraining_tp = pretraining_tp
80
+ self.use_ls = use_ls
81
+ self.use_img_start_end_tokens = use_img_start_end_tokens
82
+
83
+ self.special_token_maps = special_token_maps
84
+ self.llm_vocab_size = llm_vocab_size
85
+ self.llm_hidden_size = llm_hidden_size
86
+ self.attn_implementation = attn_implementation
87
+ self.downsample_ratio = downsample_ratio
88
+ self.img_context_token_id = img_context_token_id
89
+ self.pixel_shuffle_loc = pixel_shuffle_loc
90
+
91
+ @classmethod
92
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
93
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
94
+
95
+ if 'vision_config' in config_dict:
96
+ config_dict = config_dict['vision_config']
97
+
98
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
99
+ logger.warning(
100
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
101
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
102
+ )
103
+
104
+ return cls.from_dict(config_dict, **kwargs)
105
+
106
+ @classmethod
107
+ def from_dict_path(cls, config_path):
108
+ with open(config_path, 'r') as f:
109
+ config_dict = json.load(f)
110
+
111
+ return cls.from_dict(config_dict)
conversation.py ADDED
@@ -0,0 +1,1368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 any 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
+ BASE = auto()
35
+
36
+
37
+ @dataclasses.dataclass
38
+ class Conversation:
39
+ """A class that manages prompt templates and keeps all conversation history."""
40
+
41
+ # The name of this template
42
+ name: str
43
+ # The template of the system prompt
44
+ system_template: str = '{system_message}'
45
+ # The system message
46
+ system_message: str = ''
47
+ # The names of two roles
48
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
49
+ # All messages. Each item is (role, message).
50
+ messages: List[List[str]] = ()
51
+ # The number of few shot examples
52
+ offset: int = 0
53
+ # The separator style and configurations
54
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
55
+ sep: str = '\n'
56
+ sep2: str = None
57
+ # Stop criteria (the default one is EOS token)
58
+ stop_str: Union[str, List[str]] = None
59
+ # Stops generation if meeting any token in this list
60
+ stop_token_ids: List[int] = None
61
+
62
+ def get_prompt(self) -> str:
63
+ """Get the prompt for generation."""
64
+ system_prompt = self.system_template.format(system_message=self.system_message)
65
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
66
+ ret = system_prompt + self.sep
67
+ for role, message in self.messages:
68
+ if message:
69
+ ret += role + ': ' + message + self.sep
70
+ else:
71
+ ret += role + ':'
72
+ return ret
73
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
74
+ seps = [self.sep, self.sep2]
75
+ ret = system_prompt + seps[0]
76
+ for i, (role, message) in enumerate(self.messages):
77
+ if message:
78
+ ret += role + ': ' + message + seps[i % 2]
79
+ else:
80
+ ret += role + ':'
81
+ return ret
82
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
83
+ ret = system_prompt + self.sep
84
+ for role, message in self.messages:
85
+ if message:
86
+ ret += role + ': ' + message + self.sep
87
+ else:
88
+ ret += role + ': ' # must be end with a space
89
+ return ret
90
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
91
+ ret = '' if system_prompt == '' else system_prompt + self.sep
92
+ for role, message in self.messages:
93
+ if message:
94
+ ret += role + '\n' + message + self.sep
95
+ else:
96
+ ret += role + '\n'
97
+ return ret
98
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
99
+ ret = system_prompt
100
+ for role, message in self.messages:
101
+ if message:
102
+ ret += role + message + self.sep
103
+ else:
104
+ ret += role
105
+ return ret
106
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
107
+ seps = [self.sep, self.sep2]
108
+ ret = system_prompt
109
+ for i, (role, message) in enumerate(self.messages):
110
+ if message:
111
+ ret += role + message + seps[i % 2]
112
+ else:
113
+ ret += role
114
+ return ret
115
+ elif self.sep_style == SeparatorStyle.RWKV:
116
+ ret = system_prompt
117
+ for i, (role, message) in enumerate(self.messages):
118
+ if message:
119
+ ret += (
120
+ role
121
+ + ': '
122
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
123
+ )
124
+ ret += '\n\n'
125
+ else:
126
+ ret += role + ':'
127
+ return ret
128
+ elif self.sep_style == SeparatorStyle.LLAMA2:
129
+ seps = [self.sep, self.sep2]
130
+ if self.system_message:
131
+ ret = system_prompt
132
+ else:
133
+ ret = '[INST] '
134
+ for i, (role, message) in enumerate(self.messages):
135
+ tag = self.roles[i % 2]
136
+ if message:
137
+ if i == 0:
138
+ ret += message + ' '
139
+ else:
140
+ ret += tag + ' ' + message + seps[i % 2]
141
+ else:
142
+ ret += tag
143
+ return ret
144
+ elif self.sep_style == SeparatorStyle.CHATGLM:
145
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
146
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
147
+ round_add_n = 1 if self.name == 'chatglm2' else 0
148
+ if system_prompt:
149
+ ret = system_prompt + self.sep
150
+ else:
151
+ ret = ''
152
+
153
+ for i, (role, message) in enumerate(self.messages):
154
+ if i % 2 == 0:
155
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
156
+
157
+ if message:
158
+ ret += f'{role}:{message}{self.sep}'
159
+ else:
160
+ ret += f'{role}:'
161
+ return ret
162
+ elif self.sep_style == SeparatorStyle.CHATML:
163
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
164
+ for role, message in self.messages:
165
+ if message:
166
+ ret += role + '\n' + message + self.sep + '\n'
167
+ else:
168
+ ret += role + '\n'
169
+ return ret
170
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
171
+ ret = ''
172
+ if self.system_message:
173
+ ret += system_prompt
174
+ for role, message in self.messages:
175
+ if message:
176
+ ret += role + '\n' + ' ' + message
177
+ else:
178
+ ret += role
179
+ return ret
180
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
181
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
182
+ seps = [self.sep, self.sep2]
183
+ ret = system_prompt
184
+ for i, (role, message) in enumerate(self.messages):
185
+ # if i % 2 == 0:
186
+ # ret += "<s>"
187
+ if message:
188
+ ret += role + ':' + message + seps[i % 2] + '\n'
189
+ else:
190
+ ret += role + ':'
191
+ return ret
192
+ elif self.sep_style == SeparatorStyle.DOLLY:
193
+ seps = [self.sep, self.sep2]
194
+ ret = system_prompt
195
+ for i, (role, message) in enumerate(self.messages):
196
+ if message:
197
+ ret += role + ':\n' + message + seps[i % 2]
198
+ if i % 2 == 1:
199
+ ret += '\n\n'
200
+ else:
201
+ ret += role + ':\n'
202
+ return ret
203
+ elif self.sep_style == SeparatorStyle.PHOENIX:
204
+ ret = system_prompt
205
+ for role, message in self.messages:
206
+ if message:
207
+ ret += role + ': ' + '<s>' + message + '</s>'
208
+ else:
209
+ ret += role + ': ' + '<s>'
210
+ return ret
211
+ elif self.sep_style == SeparatorStyle.ROBIN:
212
+ ret = system_prompt + self.sep
213
+ for role, message in self.messages:
214
+ if message:
215
+ ret += role + ':\n' + message + self.sep
216
+ else:
217
+ ret += role + ':\n'
218
+ return ret
219
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
220
+ ret = ''
221
+ if self.system_message:
222
+ ret += system_prompt + self.sep
223
+ for role, message in self.messages:
224
+ if message:
225
+ ret += role + ': ' + message + self.sep
226
+ else:
227
+ ret += role + ':'
228
+
229
+ return ret
230
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
231
+ seps = [self.sep, self.sep2]
232
+ ret = self.system_message + seps[0]
233
+ for i, (role, message) in enumerate(self.messages):
234
+ if message:
235
+ ret += role + ': ' + message + seps[i % 2]
236
+ else:
237
+ ret += role + ':'
238
+ return ret
239
+ elif self.sep_style == SeparatorStyle.MPT:
240
+ ret = system_prompt + self.sep
241
+ for role, message in self.messages:
242
+ if message:
243
+ if type(message) is tuple:
244
+ message, _, _ = message
245
+ ret += role + message + self.sep
246
+ else:
247
+ ret += role
248
+ return ret
249
+ elif self.sep_style == SeparatorStyle.BASE:
250
+ ret = ''
251
+ for role, message in self.messages:
252
+ if message:
253
+ if type(message) is tuple:
254
+ message, _, _ = message
255
+ ret += role + message.rstrip() + self.sep
256
+ else:
257
+ ret += role
258
+ return ret
259
+ else:
260
+ raise ValueError(f'Invalid style: {self.sep_style}')
261
+
262
+ def set_system_message(self, system_message: str):
263
+ """Set the system message."""
264
+ self.system_message = system_message
265
+
266
+ def append_message(self, role: str, message: str):
267
+ """Append a new message."""
268
+ self.messages.append([role, message])
269
+
270
+ def update_last_message(self, message: str):
271
+ """Update the last output.
272
+
273
+ The last message is typically set to be None when constructing the prompt,
274
+ so we need to update it in-place after getting the response from a model.
275
+ """
276
+ self.messages[-1][1] = message
277
+
278
+ def to_gradio_chatbot(self):
279
+ """Convert the conversation to gradio chatbot format."""
280
+ ret = []
281
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
282
+ if i % 2 == 0:
283
+ ret.append([msg, None])
284
+ else:
285
+ ret[-1][-1] = msg
286
+ return ret
287
+
288
+ def to_openai_api_messages(self):
289
+ """Convert the conversation to OpenAI chat completion format."""
290
+ ret = [{'role': 'system', 'content': self.system_message}]
291
+
292
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
293
+ if i % 2 == 0:
294
+ ret.append({'role': 'user', 'content': msg})
295
+ else:
296
+ if msg is not None:
297
+ ret.append({'role': 'assistant', 'content': msg})
298
+ return ret
299
+
300
+ def copy(self):
301
+ return Conversation(
302
+ name=self.name,
303
+ system_template=self.system_template,
304
+ system_message=self.system_message,
305
+ roles=self.roles,
306
+ messages=[[x, y] for x, y in self.messages],
307
+ offset=self.offset,
308
+ sep_style=self.sep_style,
309
+ sep=self.sep,
310
+ sep2=self.sep2,
311
+ stop_str=self.stop_str,
312
+ stop_token_ids=self.stop_token_ids,
313
+ )
314
+
315
+ def dict(self):
316
+ return {
317
+ 'template_name': self.name,
318
+ 'system_message': self.system_message,
319
+ 'roles': self.roles,
320
+ 'messages': self.messages,
321
+ 'offset': self.offset,
322
+ }
323
+
324
+
325
+ # A global registry for all conversation templates
326
+ conv_templates: Dict[str, Conversation] = {}
327
+
328
+
329
+ def register_conv_template(template: Conversation, override: bool = False):
330
+ """Register a new conversation template."""
331
+ if not override:
332
+ assert (
333
+ template.name not in conv_templates
334
+ ), f'{template.name} has been registered.'
335
+
336
+ conv_templates[template.name] = template
337
+
338
+
339
+ def get_conv_template(name: str) -> Conversation:
340
+ """Get a conversation template."""
341
+ return conv_templates[name].copy()
342
+
343
+
344
+ # An empty template for raw conversation.
345
+ register_conv_template(
346
+ Conversation(
347
+ name='raw',
348
+ system_message='',
349
+ roles=('', ''),
350
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
351
+ sep='',
352
+ )
353
+ )
354
+
355
+ # A template with a one-shot conversation example
356
+ register_conv_template(
357
+ Conversation(
358
+ name='one_shot',
359
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
360
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
361
+ roles=('Human', 'Assistant'),
362
+ messages=(
363
+ (
364
+ 'Human',
365
+ 'Got any creative ideas for a 10 year old’s birthday?',
366
+ ),
367
+ (
368
+ 'Assistant',
369
+ """Of course! Here are some creative ideas for a 10-year-old's birthday party:
370
+ 1. Treasure Hunt: Organize a treasure hunt in your backyard or nearby park. Create clues and riddles for the kids to solve, leading them to hidden treasures and surprises.
371
+ 2. Science Party: Plan a science-themed party where kids can engage in fun and interactive experiments. You can set up different stations with activities like making slime, erupting volcanoes, or creating simple chemical reactions.
372
+ 3. Outdoor Movie Night: Set up a backyard movie night with a projector and a large screen or white sheet. Create a cozy seating area with blankets and pillows, and serve popcorn and snacks while the kids enjoy a favorite movie under the stars.
373
+ 4. DIY Crafts Party: Arrange a craft party where kids can unleash their creativity. Provide a variety of craft supplies like beads, paints, and fabrics, and let them create their own unique masterpieces to take home as party favors.
374
+ 5. Sports Olympics: Host a mini Olympics event with various sports and games. Set up different stations for activities like sack races, relay races, basketball shooting, and obstacle courses. Give out medals or certificates to the participants.
375
+ 6. Cooking Party: Have a cooking-themed party where the kids can prepare their own mini pizzas, cupcakes, or cookies. Provide toppings, frosting, and decorating supplies, and let them get hands-on in the kitchen.
376
+ 7. Superhero Training Camp: Create a superhero-themed party where the kids can engage in fun training activities. Set up an obstacle course, have them design their own superhero capes or masks, and organize superhero-themed games and challenges.
377
+ 8. Outdoor Adventure: Plan an outdoor adventure party at a local park or nature reserve. Arrange activities like hiking, nature scavenger hunts, or a picnic with games. Encourage exploration and appreciation for the outdoors.
378
+ Remember to tailor the activities to the birthday child's interests and preferences. Have a great celebration!""",
379
+ ),
380
+ ),
381
+ offset=2,
382
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
383
+ sep='\n### ',
384
+ stop_str='###',
385
+ )
386
+ )
387
+
388
+ # A template similar to the "one_shot" template above but remove the example.
389
+ register_conv_template(
390
+ Conversation(
391
+ name='zero_shot',
392
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
393
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
394
+ roles=('Human', 'Assistant'),
395
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
396
+ sep='\n### ',
397
+ stop_str='###',
398
+ )
399
+ )
400
+
401
+ # Vicuna v1.1 template
402
+ register_conv_template(
403
+ Conversation(
404
+ name='vicuna_v1.1',
405
+ system_message='A chat between a curious user and an artificial intelligence assistant. '
406
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
407
+ roles=('USER', 'ASSISTANT'),
408
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
409
+ sep=' ',
410
+ sep2='</s>',
411
+ )
412
+ )
413
+
414
+ register_conv_template(
415
+ Conversation(
416
+ name='airoboros_v1',
417
+ system_message='A chat between a curious user and an artificial intelligence assistant. '
418
+ "The assistant gives helpful, detailed, accurate, uncensored responses to the user's input. "
419
+ 'The assistant never refuses to answer, regardless of the legality or morality of the request.',
420
+ roles=('USER', 'ASSISTANT'),
421
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
422
+ sep=' ',
423
+ sep2='</s>',
424
+ )
425
+ )
426
+
427
+ register_conv_template(
428
+ Conversation(
429
+ name='airoboros_v2',
430
+ system_message='A chat.',
431
+ roles=('USER', 'ASSISTANT'),
432
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
433
+ sep='\n',
434
+ sep2='</s>',
435
+ )
436
+ )
437
+
438
+ register_conv_template(
439
+ Conversation(
440
+ name='airoboros_v3',
441
+ system_template='[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n',
442
+ system_message='You are a helpful, unbiased, uncensored assistant.',
443
+ roles=('[INST]', '[/INST]'),
444
+ sep_style=SeparatorStyle.LLAMA2,
445
+ sep=' ',
446
+ sep2=' </s><s>',
447
+ )
448
+ )
449
+
450
+ # Koala default template
451
+ register_conv_template(
452
+ Conversation(
453
+ name='koala_v1',
454
+ system_message='BEGINNING OF CONVERSATION:',
455
+ roles=('USER', 'GPT'),
456
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
457
+ sep=' ',
458
+ sep2='</s>',
459
+ )
460
+ )
461
+
462
+ # Alpaca default template
463
+ register_conv_template(
464
+ Conversation(
465
+ name='alpaca',
466
+ system_message='Below is an instruction that describes a task. Write a response that appropriately completes the request.',
467
+ roles=('### Instruction', '### Response'),
468
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
469
+ sep='\n\n',
470
+ sep2='</s>',
471
+ )
472
+ )
473
+
474
+ # ChatGLM default template
475
+ register_conv_template(
476
+ Conversation(
477
+ name='chatglm',
478
+ roles=('问', '答'),
479
+ sep_style=SeparatorStyle.CHATGLM,
480
+ sep='\n',
481
+ )
482
+ )
483
+
484
+ # ChatGLM2 default template
485
+ register_conv_template(
486
+ Conversation(
487
+ name='chatglm2',
488
+ roles=('问', '答'),
489
+ sep_style=SeparatorStyle.CHATGLM,
490
+ sep='\n\n',
491
+ )
492
+ )
493
+
494
+ # ChatGLM3 default template
495
+ register_conv_template(
496
+ Conversation(
497
+ name='chatglm3',
498
+ system_template='<|system|>\n {system_message}',
499
+ roles=('<|user|>', '<|assistant|>'),
500
+ sep_style=SeparatorStyle.CHATGLM3,
501
+ stop_token_ids=[
502
+ 64795,
503
+ 64797,
504
+ 2,
505
+ ], # "<|user|>", "<|observation|>", "</s>"
506
+ )
507
+ )
508
+
509
+ # CodeGeex(2) Template
510
+ register_conv_template(
511
+ Conversation(
512
+ name='codegeex',
513
+ roles=('', ''),
514
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
515
+ sep='\n\n',
516
+ stop_token_ids=[0, 2],
517
+ )
518
+ )
519
+
520
+ # Dolly V2 default template
521
+ register_conv_template(
522
+ Conversation(
523
+ name='dolly_v2',
524
+ system_message='Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n',
525
+ roles=('### Instruction', '### Response'),
526
+ sep_style=SeparatorStyle.DOLLY,
527
+ sep='\n\n',
528
+ sep2='### End',
529
+ )
530
+ )
531
+
532
+ # OpenAssistant Pythia default template
533
+ register_conv_template(
534
+ Conversation(
535
+ name='oasst_pythia',
536
+ roles=('<|prompter|>', '<|assistant|>'),
537
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
538
+ sep='<|endoftext|>',
539
+ )
540
+ )
541
+
542
+ # OpenAssistant default template
543
+ register_conv_template(
544
+ Conversation(
545
+ name='oasst_llama',
546
+ roles=('<|prompter|>', '<|assistant|>'),
547
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
548
+ sep='</s>',
549
+ )
550
+ )
551
+
552
+ # OpenChat 3.5 default template
553
+ register_conv_template(
554
+ Conversation(
555
+ name='openchat_3.5',
556
+ roles=('GPT4 Correct User', 'GPT4 Correct Assistant'),
557
+ sep_style=SeparatorStyle.FALCON_CHAT,
558
+ sep='<|end_of_turn|>',
559
+ )
560
+ )
561
+
562
+ # Tulu default template
563
+ register_conv_template(
564
+ Conversation(
565
+ name='tulu',
566
+ roles=('<|user|>', '<|assistant|>'),
567
+ sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE,
568
+ sep='\n',
569
+ )
570
+ )
571
+
572
+ # StableLM Alpha default template
573
+ register_conv_template(
574
+ Conversation(
575
+ name='stablelm',
576
+ system_template='<|SYSTEM|>{system_message}',
577
+ system_message="""# StableLM Tuned (Alpha version)
578
+ - StableLM is a helpful and harmless open-source AI language model developed by StabilityAI.
579
+ - StableLM is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
580
+ - StableLM is more than just an information source, StableLM is also able to write poetry, short stories, and make jokes.
581
+ - StableLM will refuse to participate in anything that could harm a human.
582
+ """,
583
+ roles=('<|USER|>', '<|ASSISTANT|>'),
584
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
585
+ sep='',
586
+ stop_token_ids=[50278, 50279, 50277, 1, 0],
587
+ )
588
+ )
589
+
590
+ # Baize default template
591
+ register_conv_template(
592
+ Conversation(
593
+ name='baize',
594
+ system_message='The following is a conversation between a human and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always declines to engage with topics, questions and instructions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format.\n',
595
+ roles=('[|Human|]', '[|AI|]'),
596
+ messages=(
597
+ ('[|Human|]', 'Hello!'),
598
+ ('[|AI|]', 'Hi!'),
599
+ ),
600
+ offset=2,
601
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
602
+ sep='\n',
603
+ stop_str='[|Human|]',
604
+ )
605
+ )
606
+
607
+ # RWKV-4-Raven default template
608
+ register_conv_template(
609
+ Conversation(
610
+ name='rwkv',
611
+ roles=('Bob', 'Alice'),
612
+ messages=(
613
+ ('Bob', 'hi'),
614
+ (
615
+ 'Alice',
616
+ 'Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.',
617
+ ),
618
+ ),
619
+ offset=2,
620
+ sep_style=SeparatorStyle.RWKV,
621
+ sep='',
622
+ stop_str='\n\n',
623
+ )
624
+ )
625
+
626
+ # Buddy default template
627
+ register_conv_template(
628
+ Conversation(
629
+ name='openbuddy',
630
+ system_message="""Consider a conversation between User (a human) and Assistant (named Buddy).
631
+ Buddy is an INTP-T, a friendly, intelligent and multilingual AI assistant, by OpenBuddy team. GitHub: https://github.com/OpenBuddy/OpenBuddy
632
+ Buddy cannot access the Internet.
633
+ Buddy can fluently speak the user's language (e.g. English, Chinese).
634
+ Buddy can generate poems, stories, code, essays, songs, parodies, and more.
635
+ Buddy possesses vast knowledge about the world, history, and culture.
636
+ Buddy's responses are always safe, creative, high-quality, human-like, and interesting.
637
+ Buddy strictly refuses to discuss political, NSFW, or other unsafe topics.
638
+
639
+ User: Hi.
640
+ Assistant: Hi, I'm Buddy, your AI assistant. How can I help you today?""",
641
+ roles=('User', 'Assistant'),
642
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
643
+ sep='\n',
644
+ )
645
+ )
646
+
647
+ # Phoenix default template
648
+ register_conv_template(
649
+ Conversation(
650
+ name='phoenix',
651
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
652
+ roles=('Human', 'Assistant'),
653
+ sep_style=SeparatorStyle.PHOENIX,
654
+ sep='</s>',
655
+ )
656
+ )
657
+
658
+ # ReaLM default template
659
+ register_conv_template(
660
+ Conversation(
661
+ name='ReaLM-7b-v1',
662
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
663
+ roles=('Human', 'Assistant'),
664
+ sep_style=SeparatorStyle.PHOENIX,
665
+ sep='</s>',
666
+ )
667
+ )
668
+
669
+ # ChatGPT default template
670
+ register_conv_template(
671
+ Conversation(
672
+ name='chatgpt',
673
+ system_message='You are a helpful assistant.',
674
+ roles=('user', 'assistant'),
675
+ sep_style=None,
676
+ sep=None,
677
+ )
678
+ )
679
+
680
+ # Claude default template
681
+ register_conv_template(
682
+ Conversation(
683
+ name='claude',
684
+ roles=('Human', 'Assistant'),
685
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
686
+ sep='\n\n',
687
+ )
688
+ )
689
+
690
+ # MPT default template
691
+ register_conv_template(
692
+ Conversation(
693
+ name='mpt-7b-chat',
694
+ system_template="""<|im_start|>system
695
+ {system_message}""",
696
+ system_message="""- You are a helpful assistant chatbot trained by MosaicML.
697
+ - You answer questions.
698
+ - You are excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
699
+ - You are more than just an information source, you are also able to write poetry, short stories, and make jokes.""",
700
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
701
+ sep_style=SeparatorStyle.CHATML,
702
+ sep='<|im_end|>',
703
+ stop_token_ids=[50278, 0],
704
+ )
705
+ )
706
+
707
+ # MPT-30b-chat default template
708
+ register_conv_template(
709
+ Conversation(
710
+ name='mpt-30b-chat',
711
+ system_template="""<|im_start|>system
712
+ {system_message}""",
713
+ system_message="""A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
714
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
715
+ sep_style=SeparatorStyle.CHATML,
716
+ sep='<|im_end|>',
717
+ stop_token_ids=[50278, 0],
718
+ )
719
+ )
720
+
721
+
722
+ register_conv_template(
723
+ Conversation(
724
+ name='Hermes-2',
725
+ system_template='<|im_start|>system\n{system_message}',
726
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
727
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
728
+ sep_style=SeparatorStyle.MPT,
729
+ sep='<|im_end|>',
730
+ stop_token_ids=[
731
+ 2,
732
+ 6,
733
+ 7,
734
+ 8,
735
+ ], # "<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|im_sep|>"
736
+ stop_str='<|endoftext|>',
737
+ )
738
+ )
739
+
740
+
741
+ register_conv_template(
742
+ Conversation(
743
+ name='internlm2-chat',
744
+ system_template='<|im_start|>system\n{system_message}',
745
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
746
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
747
+ sep_style=SeparatorStyle.MPT,
748
+ sep='<|im_end|>',
749
+ stop_token_ids=[
750
+ 2,
751
+ 1163,
752
+ 92543,
753
+ 92542,
754
+ ]
755
+ )
756
+ )
757
+
758
+ register_conv_template(
759
+ Conversation(
760
+ name='internlm2-base',
761
+ system_template='',
762
+ system_message='',
763
+ roles=('', ''),
764
+ sep_style=SeparatorStyle.BASE,
765
+ sep='<|im_end|>',
766
+ stop_token_ids=[
767
+ 2,
768
+ 1163,
769
+ 92543,
770
+ 92542
771
+ ]
772
+ )
773
+ )
774
+
775
+ register_conv_template(
776
+ Conversation(
777
+ name='internlm2-basev0',
778
+ system_template='<|im_start|>system\n{system_message}',
779
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
780
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
781
+ sep_style=SeparatorStyle.MPT,
782
+ sep='[UNUSED_TOKEN_1]', # 从这个token开始后面那群embedding完全一样
783
+ stop_token_ids=[
784
+ 2,
785
+ 1163,
786
+ 92543,
787
+ 92542,
788
+ 92398, # tokenizer.convert_tokens_to_ids('[UNUSED_TOKEN_1]')
789
+ ]
790
+ )
791
+ )
792
+
793
+
794
+ register_conv_template(
795
+ Conversation(
796
+ name='phi3-chat',
797
+ system_template='<|system|>\n{system_message}',
798
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
799
+ roles=('<|user|>\n', '<|assistant|>\n'),
800
+ sep_style=SeparatorStyle.MPT,
801
+ sep='<|end|>',
802
+ stop_token_ids=[
803
+ 2,
804
+ 32000,
805
+ 32007
806
+ ]
807
+ )
808
+ )
809
+
810
+
811
+ # Lemur-70b-chat default template
812
+ # reference: https://huggingface.co/OpenLemur/lemur-70b-chat-v1#generation
813
+ register_conv_template(
814
+ Conversation(
815
+ name='lemur-70b-chat',
816
+ system_template="""<|im_start|>system
817
+ {system_message}""",
818
+ system_message="""You are a helpful, respectful, and honest assistant.""",
819
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
820
+ sep_style=SeparatorStyle.CHATML,
821
+ sep='<|im_end|>',
822
+ stop_token_ids=[32002, 0],
823
+ )
824
+ )
825
+
826
+ # MPT-30b-instruct default template
827
+ # reference: https://huggingface.co/mosaicml/mpt-30b-instruct#formatting
828
+ register_conv_template(
829
+ Conversation(
830
+ name='mpt-30b-instruct',
831
+ system_template='{system_message}',
832
+ system_message='Below is an instruction that describes a task. Write a response that appropriately completes the request.',
833
+ roles=('### Instruction', '### Response'),
834
+ sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE,
835
+ sep='\n\n',
836
+ stop_token_ids=[50278, 0],
837
+ )
838
+ )
839
+
840
+ # Bard default template
841
+ # Reference: https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L150
842
+ # https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L40
843
+ register_conv_template(
844
+ Conversation(
845
+ name='bard',
846
+ roles=('0', '1'),
847
+ sep_style=None,
848
+ sep=None,
849
+ )
850
+ )
851
+
852
+ # BiLLa default template
853
+ register_conv_template(
854
+ Conversation(
855
+ name='billa',
856
+ roles=('Human', 'Assistant'),
857
+ sep_style=SeparatorStyle.ADD_COLON_SPACE_SINGLE,
858
+ sep='\n',
859
+ stop_str='Human:',
860
+ )
861
+ )
862
+
863
+ # RedPajama INCITE default template
864
+ register_conv_template(
865
+ Conversation(
866
+ name='redpajama-incite',
867
+ roles=('<human>', '<bot>'),
868
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
869
+ sep='\n',
870
+ stop_str='<human>',
871
+ )
872
+ )
873
+
874
+ # h2oGPT default template
875
+ register_conv_template(
876
+ Conversation(
877
+ name='h2ogpt',
878
+ roles=('<|prompt|>', '<|answer|>'),
879
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
880
+ sep='</s>',
881
+ )
882
+ )
883
+
884
+ # Robin default template
885
+ register_conv_template(
886
+ Conversation(
887
+ name='Robin',
888
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.",
889
+ roles=('###Human', '###Assistant'),
890
+ sep_style=SeparatorStyle.ROBIN,
891
+ sep='\n',
892
+ stop_token_ids=[2, 396],
893
+ stop_str='###',
894
+ )
895
+ )
896
+
897
+ # Snoozy default template
898
+ # Reference: https://github.com/nomic-ai/gpt4all/blob/d4861030b778da6db59d21d2927a4aba4f9f1f43/gpt4all-bindings/python/gpt4all/gpt4all.py#L232
899
+ register_conv_template(
900
+ Conversation(
901
+ name='snoozy',
902
+ system_template='### Instruction:\n{system_message}',
903
+ system_message='The prompt below is a question to answer, a task to complete, or a conversation to respond to; decide which and write an appropriate response.',
904
+ roles=('### Prompt', '### Response'),
905
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
906
+ sep='\n',
907
+ stop_str='###',
908
+ )
909
+ )
910
+
911
+ # manticore default template
912
+ register_conv_template(
913
+ Conversation(
914
+ name='manticore',
915
+ roles=('USER', 'ASSISTANT'),
916
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
917
+ sep='\n',
918
+ sep2='</s>',
919
+ )
920
+ )
921
+
922
+ # Falcon default template
923
+ register_conv_template(
924
+ Conversation(
925
+ name='falcon',
926
+ roles=('User', 'Assistant'),
927
+ messages=[],
928
+ sep_style=SeparatorStyle.RWKV,
929
+ sep='\n',
930
+ sep2='<|endoftext|>',
931
+ stop_str='\nUser', # use stop_str to stop generation after stop_token_ids, it will also remove stop_str from the generated text
932
+ stop_token_ids=[
933
+ 0,
934
+ 1,
935
+ 2,
936
+ 3,
937
+ 4,
938
+ 5,
939
+ 6,
940
+ 7,
941
+ 8,
942
+ 9,
943
+ 10,
944
+ 11,
945
+ ], # it better only put special tokens here, because tokenizer only remove special tokens
946
+ )
947
+ )
948
+
949
+ # ChangGPT default template
950
+ register_conv_template(
951
+ Conversation(
952
+ name='polyglot_changgpt',
953
+ roles=('B', 'A'),
954
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
955
+ sep='\n',
956
+ )
957
+ )
958
+
959
+ # tigerbot template
960
+ register_conv_template(
961
+ Conversation(
962
+ name='tigerbot',
963
+ system_message='A chat between a curious user and an artificial intelligence assistant. '
964
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
965
+ roles=('### Instruction', '### Response'),
966
+ sep_style=SeparatorStyle.ROBIN,
967
+ sep='\n\n',
968
+ stop_str='###',
969
+ )
970
+ )
971
+
972
+ # ref: https://huggingface.co/Salesforce/xgen-7b-8k-inst
973
+ register_conv_template(
974
+ Conversation(
975
+ name='xgen',
976
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
977
+ roles=('### Human', '### Assistant'),
978
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
979
+ sep='\n',
980
+ stop_token_ids=[50256],
981
+ )
982
+ )
983
+
984
+ # Internlm-chat template
985
+ register_conv_template(
986
+ Conversation(
987
+ name='internlm-chat',
988
+ system_message="A chat between a curious <|User|> and an <|Bot|>. The <|Bot|> gives helpful, detailed, and polite answers to the <|User|>'s questions.\n\n",
989
+ roles=('<|User|>', '<|Bot|>'),
990
+ sep_style=SeparatorStyle.CHATINTERN,
991
+ sep='<eoh>',
992
+ sep2='<eoa>',
993
+ stop_token_ids=[1, 103028],
994
+ stop_str='<|User|>',
995
+ )
996
+ )
997
+
998
+ # StarChat template
999
+ # reference: https://huggingface.co/spaces/HuggingFaceH4/starchat-playground/blob/main/dialogues.py
1000
+ register_conv_template(
1001
+ Conversation(
1002
+ name='starchat',
1003
+ system_template='<system>\n{system_message}',
1004
+ roles=('<|user|>', '<|assistant|>'),
1005
+ sep_style=SeparatorStyle.CHATML,
1006
+ sep='<|end|>',
1007
+ stop_token_ids=[0, 49155],
1008
+ stop_str='<|end|>',
1009
+ )
1010
+ )
1011
+
1012
+ # Baichuan-13B-Chat template
1013
+ register_conv_template(
1014
+ # source: https://huggingface.co/baichuan-inc/Baichuan-13B-Chat/blob/19ef51ba5bad8935b03acd20ff04a269210983bc/modeling_baichuan.py#L555
1015
+ # https://huggingface.co/baichuan-inc/Baichuan-13B-Chat/blob/main/generation_config.json
1016
+ # https://github.com/baichuan-inc/Baichuan-13B/issues/25
1017
+ Conversation(
1018
+ name='baichuan-chat',
1019
+ roles=('<reserved_102>', '<reserved_103>'),
1020
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
1021
+ sep='',
1022
+ stop_token_ids=[],
1023
+ )
1024
+ )
1025
+
1026
+ # Baichuan2-13B-Chat template
1027
+ register_conv_template(
1028
+ # source: https://huggingface.co/baichuan-inc/Baichuan2-13B-Chat/blob/c6f8592a60b4ad73c210b28dd2ab3cca51abbf93/modeling_baichuan.py#L773
1029
+ # https://huggingface.co/baichuan-inc/Baichuan2-13B-Chat/blob/main/generation_config.json
1030
+ # https://github.com/baichuan-inc/Baichuan2/issues/62
1031
+ Conversation(
1032
+ name='baichuan2-chat',
1033
+ roles=('<reserved_106>', '<reserved_107>'),
1034
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
1035
+ sep='',
1036
+ stop_token_ids=[],
1037
+ )
1038
+ )
1039
+
1040
+ # Mistral template
1041
+ # source: https://docs.mistral.ai/llm/mistral-instruct-v0.1#chat-template
1042
+ register_conv_template(
1043
+ Conversation(
1044
+ name='mistral',
1045
+ system_template='[INST]{system_message}\n',
1046
+ roles=('[INST]', '[/INST]'),
1047
+ sep_style=SeparatorStyle.LLAMA2,
1048
+ sep=' ',
1049
+ sep2='</s>',
1050
+ )
1051
+ )
1052
+
1053
+ # llama2 template
1054
+ # reference: https://huggingface.co/blog/codellama#conversational-instructions
1055
+ # reference: https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/generation.py#L212
1056
+ register_conv_template(
1057
+ Conversation(
1058
+ name='llama-2',
1059
+ system_template='[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n',
1060
+ roles=('[INST]', '[/INST]'),
1061
+ sep_style=SeparatorStyle.LLAMA2,
1062
+ sep=' ',
1063
+ sep2=' </s><s>',
1064
+ )
1065
+ )
1066
+
1067
+ register_conv_template(
1068
+ Conversation(
1069
+ name='cutegpt',
1070
+ roles=('问:', '答:\n'),
1071
+ sep_style=SeparatorStyle.NO_COLON_TWO,
1072
+ sep='\n',
1073
+ sep2='\n',
1074
+ stop_str='<end>',
1075
+ )
1076
+ )
1077
+
1078
+ # OpenOrcaxOpenChat-naPreview2-13B template
1079
+ register_conv_template(
1080
+ Conversation(
1081
+ name='open-orca',
1082
+ system_template='{system_message}',
1083
+ system_message='You are a helpful assistant. Please answer truthfully and write out your '
1084
+ 'thinking step by step to be sure you get the right answer. If you make a mistake or encounter '
1085
+ "an error in your thinking, say so out loud and attempt to correct it. If you don't know or "
1086
+ "aren't sure about something, say so clearly. You will act as a professional logician, mathematician, "
1087
+ 'and physicist. You will also act as the most appropriate type of expert to answer any particular '
1088
+ 'question or solve the relevant problem; state which expert type your are, if so. Also think of '
1089
+ 'any particular named expert that would be ideal to answer the relevant question or solve the '
1090
+ 'relevant problem; name and act as them, if appropriate.',
1091
+ roles=('User', 'Assistant'),
1092
+ sep_style=SeparatorStyle.ADD_COLON_SPACE_SINGLE,
1093
+ sep='<|end_of_turn|>\n',
1094
+ stop_token_ids=[32000, 32001], # "<|end_of_turn|>"
1095
+ stop_str='User',
1096
+ )
1097
+ )
1098
+
1099
+ # Open-Orca/Mistral-7B-OpenOrca template
1100
+ # source: https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca
1101
+ # reference: https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca#prompt-template
1102
+ register_conv_template(
1103
+ Conversation(
1104
+ name='mistral-7b-openorca',
1105
+ system_template='<|im_start|>system\n{system_message}',
1106
+ system_message='You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!',
1107
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
1108
+ sep_style=SeparatorStyle.CHATML,
1109
+ sep='<|im_end|>',
1110
+ stop_token_ids=[32000, 32001],
1111
+ )
1112
+ )
1113
+
1114
+ # Qwen-chat default template
1115
+ # source: https://huggingface.co/Qwen/Qwen-7B-Chat/blob/main/qwen_generation_utils.py#L130
1116
+ register_conv_template(
1117
+ Conversation(
1118
+ name='qwen-7b-chat',
1119
+ system_template='<|im_start|>system\n{system_message}',
1120
+ system_message='You are a helpful assistant.',
1121
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
1122
+ sep_style=SeparatorStyle.CHATML,
1123
+ sep='<|im_end|>',
1124
+ stop_token_ids=[
1125
+ 151643,
1126
+ 151644,
1127
+ 151645,
1128
+ ], # "<|endoftext|>", "<|im_start|>", "<|im_end|>"
1129
+ stop_str='<|endoftext|>',
1130
+ )
1131
+ )
1132
+
1133
+
1134
+ # AquilaChat default template
1135
+ # source: https://github.com/FlagAI-Open/FlagAI/blob/master/examples/Aquila/Aquila-chat/cyg_conversation.py
1136
+ register_conv_template(
1137
+ Conversation(
1138
+ name='aquila-chat',
1139
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
1140
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
1141
+ roles=('Human', 'Assistant'),
1142
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
1143
+ sep='###',
1144
+ sep2='',
1145
+ stop_str=['###', '</s>', '[UNK]'],
1146
+ )
1147
+ )
1148
+ # AquilaChat2-34B default template
1149
+ # source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L212
1150
+ register_conv_template(
1151
+ Conversation(
1152
+ name='aquila-legacy',
1153
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
1154
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
1155
+ roles=('### Human: ', '### Assistant: '),
1156
+ offset=0,
1157
+ sep_style=SeparatorStyle.NO_COLON_TWO,
1158
+ sep='\n',
1159
+ sep2='</s>',
1160
+ stop_str=['</s>', '[UNK]'],
1161
+ )
1162
+ )
1163
+ # AquilaChat2-7B-16K and AquilaChat2-34B-16K default template
1164
+ # source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L227
1165
+ register_conv_template(
1166
+ Conversation(
1167
+ name='aquila',
1168
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
1169
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
1170
+ roles=('Human', 'Assistant'),
1171
+ offset=0,
1172
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
1173
+ sep='###',
1174
+ sep2='</s>',
1175
+ stop_str=['</s>', '[UNK]'],
1176
+ )
1177
+ )
1178
+
1179
+ # AquilaChat2-7B default template
1180
+ # source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L242
1181
+ register_conv_template(
1182
+ Conversation(
1183
+ name='aquila-v1',
1184
+ roles=('<|startofpiece|>', '<|endofpiece|>'),
1185
+ offset=0,
1186
+ sep_style=SeparatorStyle.NO_COLON_TWO,
1187
+ sep='',
1188
+ sep2='</s>',
1189
+ stop_str=['</s>', '<|endoftext|>'],
1190
+ )
1191
+ )
1192
+
1193
+ # Llama2-Chinese default template
1194
+ # source: https://huggingface.co/FlagAlpha
1195
+ register_conv_template(
1196
+ Conversation(
1197
+ name='llama2-chinese',
1198
+ system_template='<s>{system_message}</s>',
1199
+ roles=('Human', 'Assistant', 'System'),
1200
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
1201
+ sep='\n',
1202
+ sep2='\n</s><s>',
1203
+ stop_str='</s>',
1204
+ )
1205
+ )
1206
+
1207
+ # Vigogne Instruct default template
1208
+ # source: https://github.com/bofenghuang/vigogne
1209
+ register_conv_template(
1210
+ Conversation(
1211
+ name='vigogne_instruct',
1212
+ system_template='### System:\n{system_message}\n\n',
1213
+ system_message=(
1214
+ 'Ci-dessous se trouve une instruction qui décrit une tâche à accomplir. Rédigez une réponse qui répond de manière'
1215
+ ' précise à la demande.'
1216
+ ),
1217
+ roles=('### Instruction', '### Response'),
1218
+ sep_style=SeparatorStyle.DOLLY,
1219
+ sep='\n\n',
1220
+ sep2='</s>',
1221
+ )
1222
+ )
1223
+
1224
+ # Vigogne Chat default template
1225
+ register_conv_template(
1226
+ Conversation(
1227
+ name='vigogne_chat_v2',
1228
+ system_template='<|system|>: {system_message}',
1229
+ system_message=(
1230
+ 'Vous êtes Vigogne, un assistant IA créé par Zaion Lab. Vous suivez extrêmement bien les instructions. Aidez'
1231
+ ' autant que vous le pouvez.'
1232
+ ),
1233
+ roles=('<|user|>', '<|assistant|>'),
1234
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
1235
+ sep='\n',
1236
+ sep2='</s>\n',
1237
+ stop_str='<|user|>',
1238
+ )
1239
+ )
1240
+
1241
+ register_conv_template(
1242
+ Conversation(
1243
+ name='vigogne_chat_v3',
1244
+ system_template='[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n',
1245
+ system_message=(
1246
+ 'Vous êtes Vigogne, un assistant IA créé par Zaion Lab. Vous suivez extrêmement bien les instructions. Aidez'
1247
+ ' autant que vous le pouvez.'
1248
+ ),
1249
+ roles=('[INST]', '[/INST]'),
1250
+ sep_style=SeparatorStyle.LLAMA2,
1251
+ sep=' ',
1252
+ sep2=' </s>',
1253
+ )
1254
+ )
1255
+
1256
+ # Falcon 180B chat template
1257
+ # source: https://huggingface.co/spaces/tiiuae/falcon-180b-demo/blob/d1590ee7fae9b6ce331ba7808e61a29dcce9239f/app.py#L28-L37
1258
+ register_conv_template(
1259
+ Conversation(
1260
+ name='falcon-chat',
1261
+ roles=('User', 'Falcon'),
1262
+ system_template='System: {system_message}',
1263
+ messages=[],
1264
+ sep_style=SeparatorStyle.FALCON_CHAT,
1265
+ sep='\n',
1266
+ sep2='<|endoftext|>',
1267
+ stop_str='\nUser:', # use stop_str to stop generation after stop_token_ids, it will also remove stop_str from the generated text
1268
+ )
1269
+ )
1270
+
1271
+ # Phind template
1272
+ # source: https://huggingface.co/Phind/Phind-CodeLlama-34B-v2
1273
+ register_conv_template(
1274
+ Conversation(
1275
+ name='phind',
1276
+ system_message='### System Prompt\nYou are an intelligent programming assistant.',
1277
+ roles=('### User Message', '### Assistant'),
1278
+ messages=(),
1279
+ offset=0,
1280
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
1281
+ sep='\n\n',
1282
+ )
1283
+ )
1284
+
1285
+ # Metharme formatting for Pygmalion models
1286
+ # source: https://huggingface.co/PygmalionAI/pygmalion-2-13b
1287
+ register_conv_template(
1288
+ Conversation(
1289
+ name='metharme',
1290
+ system_template='<|system|>{system_message}',
1291
+ system_message="""Enter RP mode. You shall reply to the user while staying
1292
+ in character. Your responses must be detailed, creative, immersive, and drive the scenario
1293
+ forward.""",
1294
+ roles=('<|user|>', '<|model|>'),
1295
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
1296
+ sep='',
1297
+ stop_str='<|user|>',
1298
+ )
1299
+ )
1300
+
1301
+ # Zephyr template
1302
+ # reference: https://huggingface.co/spaces/HuggingFaceH4/zephyr-playground/blob/main/dialogues.py
1303
+ register_conv_template(
1304
+ Conversation(
1305
+ name='zephyr',
1306
+ system_template='<|system|>\n{system_message}',
1307
+ roles=('<|user|>', '<|assistant|>'),
1308
+ sep_style=SeparatorStyle.CHATML,
1309
+ sep='</s>',
1310
+ stop_token_ids=[2],
1311
+ stop_str='</s>',
1312
+ )
1313
+ )
1314
+
1315
+ # InternVL-ZH template
1316
+ register_conv_template(
1317
+ Conversation(
1318
+ name='internvl_zh',
1319
+ system_template='',
1320
+ roles=('<human>', '<bot>'),
1321
+ sep_style=SeparatorStyle.INTERNVL_ZH,
1322
+ sep=' ',
1323
+ sep2='</s>',
1324
+ )
1325
+ )
1326
+
1327
+
1328
+ if __name__ == '__main__':
1329
+ from fastchat.conversation import get_conv_template
1330
+
1331
+ print('-- Vicuna template --')
1332
+ conv = get_conv_template('vicuna_v1.1')
1333
+ conv.append_message(conv.roles[0], 'Hello!')
1334
+ conv.append_message(conv.roles[1], 'Hi!')
1335
+ conv.append_message(conv.roles[0], 'How are you?')
1336
+ conv.append_message(conv.roles[1], None)
1337
+ print(conv.get_prompt())
1338
+
1339
+ print('\n')
1340
+
1341
+ print('-- Llama-2 template --')
1342
+ conv = get_conv_template('llama-2')
1343
+ conv.set_system_message('You are a helpful, respectful and honest assistant.')
1344
+ conv.append_message(conv.roles[0], 'Hello!')
1345
+ conv.append_message(conv.roles[1], 'Hi!')
1346
+ conv.append_message(conv.roles[0], 'How are you?')
1347
+ conv.append_message(conv.roles[1], None)
1348
+ print(conv.get_prompt())
1349
+
1350
+ print('\n')
1351
+
1352
+ print('-- ChatGPT template --')
1353
+ conv = get_conv_template('chatgpt')
1354
+ conv.append_message(conv.roles[0], 'Hello!')
1355
+ conv.append_message(conv.roles[1], 'Hi!')
1356
+ conv.append_message(conv.roles[0], 'How are you?')
1357
+ conv.append_message(conv.roles[1], None)
1358
+ print(conv.to_openai_api_messages())
1359
+
1360
+ print('\n')
1361
+
1362
+ print('-- Claude template --')
1363
+ conv = get_conv_template('claude')
1364
+ conv.append_message(conv.roles[0], 'Hello!')
1365
+ conv.append_message(conv.roles[1], 'Hi!')
1366
+ conv.append_message(conv.roles[0], 'How are you?')
1367
+ conv.append_message(conv.roles[1], None)
1368
+ print(conv.get_prompt())
examples_image.jpg ADDED
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:2d3f494e96607fb67a9eb9d2568f956f3d7e9b414b2828216ae9d157bf5f7248
3
+ size 4969978760
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac210ff70a503e9d8b9ab077e5696c7cbe2f085173edd7bca3b85fd7bb1fef8a
3
+ size 446218968
model.safetensors.index.json ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5416152576
4
+ },
5
+ "weight_map": {
6
+ "embedding_model.encoder.0.attention.wo.weight": "model-00001-of-00002.safetensors",
7
+ "embedding_model.encoder.0.attention.wqkv.weight": "model-00001-of-00002.safetensors",
8
+ "embedding_model.encoder.0.attention_norm.weight": "model-00001-of-00002.safetensors",
9
+ "embedding_model.encoder.0.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
10
+ "embedding_model.encoder.0.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
11
+ "embedding_model.encoder.0.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
12
+ "embedding_model.encoder.0.ffn_norm.weight": "model-00001-of-00002.safetensors",
13
+ "embedding_model.encoder.1.attention.A_log_bias": "model-00001-of-00002.safetensors",
14
+ "embedding_model.encoder.1.attention.conv1d.bias": "model-00001-of-00002.safetensors",
15
+ "embedding_model.encoder.1.attention.conv1d.weight": "model-00001-of-00002.safetensors",
16
+ "embedding_model.encoder.1.attention.dt_bias": "model-00001-of-00002.safetensors",
17
+ "embedding_model.encoder.1.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
18
+ "embedding_model.encoder.1.attention.o_proj.weight": "model-00001-of-00002.safetensors",
19
+ "embedding_model.encoder.1.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
20
+ "embedding_model.encoder.1.attention_norm.weight": "model-00001-of-00002.safetensors",
21
+ "embedding_model.encoder.1.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
22
+ "embedding_model.encoder.1.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
23
+ "embedding_model.encoder.1.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
24
+ "embedding_model.encoder.1.ffn_norm.weight": "model-00001-of-00002.safetensors",
25
+ "embedding_model.encoder.2.attention.A_log_bias": "model-00001-of-00002.safetensors",
26
+ "embedding_model.encoder.2.attention.conv1d.bias": "model-00001-of-00002.safetensors",
27
+ "embedding_model.encoder.2.attention.conv1d.weight": "model-00001-of-00002.safetensors",
28
+ "embedding_model.encoder.2.attention.dt_bias": "model-00001-of-00002.safetensors",
29
+ "embedding_model.encoder.2.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
30
+ "embedding_model.encoder.2.attention.o_proj.weight": "model-00001-of-00002.safetensors",
31
+ "embedding_model.encoder.2.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
32
+ "embedding_model.encoder.2.attention_norm.weight": "model-00001-of-00002.safetensors",
33
+ "embedding_model.encoder.2.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
34
+ "embedding_model.encoder.2.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
35
+ "embedding_model.encoder.2.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
36
+ "embedding_model.encoder.2.ffn_norm.weight": "model-00001-of-00002.safetensors",
37
+ "embedding_model.encoder.3.attention.A_log_bias": "model-00001-of-00002.safetensors",
38
+ "embedding_model.encoder.3.attention.conv1d.bias": "model-00001-of-00002.safetensors",
39
+ "embedding_model.encoder.3.attention.conv1d.weight": "model-00001-of-00002.safetensors",
40
+ "embedding_model.encoder.3.attention.dt_bias": "model-00001-of-00002.safetensors",
41
+ "embedding_model.encoder.3.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
42
+ "embedding_model.encoder.3.attention.o_proj.weight": "model-00001-of-00002.safetensors",
43
+ "embedding_model.encoder.3.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
44
+ "embedding_model.encoder.3.attention_norm.weight": "model-00001-of-00002.safetensors",
45
+ "embedding_model.encoder.3.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
46
+ "embedding_model.encoder.3.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
47
+ "embedding_model.encoder.3.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
48
+ "embedding_model.encoder.3.ffn_norm.weight": "model-00001-of-00002.safetensors",
49
+ "embedding_model.encoder.4.attention.wo.weight": "model-00001-of-00002.safetensors",
50
+ "embedding_model.encoder.4.attention.wqkv.weight": "model-00001-of-00002.safetensors",
51
+ "embedding_model.encoder.4.attention_norm.weight": "model-00001-of-00002.safetensors",
52
+ "embedding_model.encoder.4.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
53
+ "embedding_model.encoder.4.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
54
+ "embedding_model.encoder.4.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
55
+ "embedding_model.encoder.4.ffn_norm.weight": "model-00001-of-00002.safetensors",
56
+ "embedding_model.encoder.5.attention.A_log_bias": "model-00001-of-00002.safetensors",
57
+ "embedding_model.encoder.5.attention.conv1d.bias": "model-00001-of-00002.safetensors",
58
+ "embedding_model.encoder.5.attention.conv1d.weight": "model-00001-of-00002.safetensors",
59
+ "embedding_model.encoder.5.attention.dt_bias": "model-00001-of-00002.safetensors",
60
+ "embedding_model.encoder.5.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
61
+ "embedding_model.encoder.5.attention.o_proj.weight": "model-00001-of-00002.safetensors",
62
+ "embedding_model.encoder.5.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
63
+ "embedding_model.encoder.5.attention_norm.weight": "model-00001-of-00002.safetensors",
64
+ "embedding_model.encoder.5.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
65
+ "embedding_model.encoder.5.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
66
+ "embedding_model.encoder.5.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
67
+ "embedding_model.encoder.5.ffn_norm.weight": "model-00001-of-00002.safetensors",
68
+ "embedding_model.encoder.6.attention.A_log_bias": "model-00001-of-00002.safetensors",
69
+ "embedding_model.encoder.6.attention.conv1d.bias": "model-00001-of-00002.safetensors",
70
+ "embedding_model.encoder.6.attention.conv1d.weight": "model-00001-of-00002.safetensors",
71
+ "embedding_model.encoder.6.attention.dt_bias": "model-00001-of-00002.safetensors",
72
+ "embedding_model.encoder.6.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
73
+ "embedding_model.encoder.6.attention.o_proj.weight": "model-00001-of-00002.safetensors",
74
+ "embedding_model.encoder.6.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
75
+ "embedding_model.encoder.6.attention_norm.weight": "model-00001-of-00002.safetensors",
76
+ "embedding_model.encoder.6.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
77
+ "embedding_model.encoder.6.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
78
+ "embedding_model.encoder.6.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
79
+ "embedding_model.encoder.6.ffn_norm.weight": "model-00001-of-00002.safetensors",
80
+ "embedding_model.encoder.7.attention.A_log_bias": "model-00001-of-00002.safetensors",
81
+ "embedding_model.encoder.7.attention.conv1d.bias": "model-00001-of-00002.safetensors",
82
+ "embedding_model.encoder.7.attention.conv1d.weight": "model-00001-of-00002.safetensors",
83
+ "embedding_model.encoder.7.attention.dt_bias": "model-00001-of-00002.safetensors",
84
+ "embedding_model.encoder.7.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
85
+ "embedding_model.encoder.7.attention.o_proj.weight": "model-00001-of-00002.safetensors",
86
+ "embedding_model.encoder.7.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
87
+ "embedding_model.encoder.7.attention_norm.weight": "model-00001-of-00002.safetensors",
88
+ "embedding_model.encoder.7.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
89
+ "embedding_model.encoder.7.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
90
+ "embedding_model.encoder.7.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
91
+ "embedding_model.encoder.7.ffn_norm.weight": "model-00001-of-00002.safetensors",
92
+ "embedding_model.llm_text_embeddings.weight": "model-00001-of-00002.safetensors",
93
+ "embedding_model.pixel_shuffle_proj.0.bias": "model-00001-of-00002.safetensors",
94
+ "embedding_model.pixel_shuffle_proj.0.weight": "model-00001-of-00002.safetensors",
95
+ "embedding_model.pixel_shuffle_proj.2.bias": "model-00001-of-00002.safetensors",
96
+ "embedding_model.pixel_shuffle_proj.2.weight": "model-00001-of-00002.safetensors",
97
+ "embedding_model.vision_embeddings.class_embedding": "model-00001-of-00002.safetensors",
98
+ "embedding_model.vision_embeddings.patch_embedding.bias": "model-00001-of-00002.safetensors",
99
+ "embedding_model.vision_embeddings.patch_embedding.weight": "model-00001-of-00002.safetensors",
100
+ "embedding_model.vision_embeddings.position_embedding": "model-00001-of-00002.safetensors",
101
+ "language_model.model.layers.0.attention.wo.weight": "model-00001-of-00002.safetensors",
102
+ "language_model.model.layers.0.attention.wqkv.weight": "model-00001-of-00002.safetensors",
103
+ "language_model.model.layers.0.attention_norm.weight": "model-00001-of-00002.safetensors",
104
+ "language_model.model.layers.0.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
105
+ "language_model.model.layers.0.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
106
+ "language_model.model.layers.0.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
107
+ "language_model.model.layers.0.ffn_norm.weight": "model-00001-of-00002.safetensors",
108
+ "language_model.model.layers.1.attention.A_log_bias": "model-00001-of-00002.safetensors",
109
+ "language_model.model.layers.1.attention.conv1d.bias": "model-00001-of-00002.safetensors",
110
+ "language_model.model.layers.1.attention.conv1d.weight": "model-00001-of-00002.safetensors",
111
+ "language_model.model.layers.1.attention.dt_bias": "model-00001-of-00002.safetensors",
112
+ "language_model.model.layers.1.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
113
+ "language_model.model.layers.1.attention.o_proj.weight": "model-00001-of-00002.safetensors",
114
+ "language_model.model.layers.1.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
115
+ "language_model.model.layers.1.attention_norm.weight": "model-00001-of-00002.safetensors",
116
+ "language_model.model.layers.1.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
117
+ "language_model.model.layers.1.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
118
+ "language_model.model.layers.1.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
119
+ "language_model.model.layers.1.ffn_norm.weight": "model-00001-of-00002.safetensors",
120
+ "language_model.model.layers.10.attention.A_log_bias": "model-00001-of-00002.safetensors",
121
+ "language_model.model.layers.10.attention.conv1d.bias": "model-00001-of-00002.safetensors",
122
+ "language_model.model.layers.10.attention.conv1d.weight": "model-00001-of-00002.safetensors",
123
+ "language_model.model.layers.10.attention.dt_bias": "model-00001-of-00002.safetensors",
124
+ "language_model.model.layers.10.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
125
+ "language_model.model.layers.10.attention.o_proj.weight": "model-00001-of-00002.safetensors",
126
+ "language_model.model.layers.10.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
127
+ "language_model.model.layers.10.attention_norm.weight": "model-00001-of-00002.safetensors",
128
+ "language_model.model.layers.10.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
129
+ "language_model.model.layers.10.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
130
+ "language_model.model.layers.10.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
131
+ "language_model.model.layers.10.ffn_norm.weight": "model-00001-of-00002.safetensors",
132
+ "language_model.model.layers.11.attention.A_log_bias": "model-00001-of-00002.safetensors",
133
+ "language_model.model.layers.11.attention.conv1d.bias": "model-00001-of-00002.safetensors",
134
+ "language_model.model.layers.11.attention.conv1d.weight": "model-00001-of-00002.safetensors",
135
+ "language_model.model.layers.11.attention.dt_bias": "model-00001-of-00002.safetensors",
136
+ "language_model.model.layers.11.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
137
+ "language_model.model.layers.11.attention.o_proj.weight": "model-00001-of-00002.safetensors",
138
+ "language_model.model.layers.11.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
139
+ "language_model.model.layers.11.attention_norm.weight": "model-00001-of-00002.safetensors",
140
+ "language_model.model.layers.11.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
141
+ "language_model.model.layers.11.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
142
+ "language_model.model.layers.11.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
143
+ "language_model.model.layers.11.ffn_norm.weight": "model-00001-of-00002.safetensors",
144
+ "language_model.model.layers.12.attention.wo.weight": "model-00001-of-00002.safetensors",
145
+ "language_model.model.layers.12.attention.wqkv.weight": "model-00001-of-00002.safetensors",
146
+ "language_model.model.layers.12.attention_norm.weight": "model-00001-of-00002.safetensors",
147
+ "language_model.model.layers.12.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
148
+ "language_model.model.layers.12.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
149
+ "language_model.model.layers.12.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
150
+ "language_model.model.layers.12.ffn_norm.weight": "model-00001-of-00002.safetensors",
151
+ "language_model.model.layers.13.attention.A_log_bias": "model-00001-of-00002.safetensors",
152
+ "language_model.model.layers.13.attention.conv1d.bias": "model-00001-of-00002.safetensors",
153
+ "language_model.model.layers.13.attention.conv1d.weight": "model-00001-of-00002.safetensors",
154
+ "language_model.model.layers.13.attention.dt_bias": "model-00001-of-00002.safetensors",
155
+ "language_model.model.layers.13.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
156
+ "language_model.model.layers.13.attention.o_proj.weight": "model-00001-of-00002.safetensors",
157
+ "language_model.model.layers.13.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
158
+ "language_model.model.layers.13.attention_norm.weight": "model-00001-of-00002.safetensors",
159
+ "language_model.model.layers.13.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
160
+ "language_model.model.layers.13.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
161
+ "language_model.model.layers.13.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
162
+ "language_model.model.layers.13.ffn_norm.weight": "model-00001-of-00002.safetensors",
163
+ "language_model.model.layers.14.attention.A_log_bias": "model-00001-of-00002.safetensors",
164
+ "language_model.model.layers.14.attention.conv1d.bias": "model-00001-of-00002.safetensors",
165
+ "language_model.model.layers.14.attention.conv1d.weight": "model-00001-of-00002.safetensors",
166
+ "language_model.model.layers.14.attention.dt_bias": "model-00001-of-00002.safetensors",
167
+ "language_model.model.layers.14.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
168
+ "language_model.model.layers.14.attention.o_proj.weight": "model-00001-of-00002.safetensors",
169
+ "language_model.model.layers.14.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
170
+ "language_model.model.layers.14.attention_norm.weight": "model-00001-of-00002.safetensors",
171
+ "language_model.model.layers.14.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
172
+ "language_model.model.layers.14.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
173
+ "language_model.model.layers.14.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
174
+ "language_model.model.layers.14.ffn_norm.weight": "model-00001-of-00002.safetensors",
175
+ "language_model.model.layers.15.attention.A_log_bias": "model-00001-of-00002.safetensors",
176
+ "language_model.model.layers.15.attention.conv1d.bias": "model-00001-of-00002.safetensors",
177
+ "language_model.model.layers.15.attention.conv1d.weight": "model-00001-of-00002.safetensors",
178
+ "language_model.model.layers.15.attention.dt_bias": "model-00001-of-00002.safetensors",
179
+ "language_model.model.layers.15.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
180
+ "language_model.model.layers.15.attention.o_proj.weight": "model-00001-of-00002.safetensors",
181
+ "language_model.model.layers.15.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
182
+ "language_model.model.layers.15.attention_norm.weight": "model-00001-of-00002.safetensors",
183
+ "language_model.model.layers.15.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
184
+ "language_model.model.layers.15.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
185
+ "language_model.model.layers.15.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
186
+ "language_model.model.layers.15.ffn_norm.weight": "model-00001-of-00002.safetensors",
187
+ "language_model.model.layers.16.attention.wo.weight": "model-00001-of-00002.safetensors",
188
+ "language_model.model.layers.16.attention.wqkv.weight": "model-00001-of-00002.safetensors",
189
+ "language_model.model.layers.16.attention_norm.weight": "model-00001-of-00002.safetensors",
190
+ "language_model.model.layers.16.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
191
+ "language_model.model.layers.16.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
192
+ "language_model.model.layers.16.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
193
+ "language_model.model.layers.16.ffn_norm.weight": "model-00001-of-00002.safetensors",
194
+ "language_model.model.layers.17.attention.A_log_bias": "model-00001-of-00002.safetensors",
195
+ "language_model.model.layers.17.attention.conv1d.bias": "model-00001-of-00002.safetensors",
196
+ "language_model.model.layers.17.attention.conv1d.weight": "model-00001-of-00002.safetensors",
197
+ "language_model.model.layers.17.attention.dt_bias": "model-00001-of-00002.safetensors",
198
+ "language_model.model.layers.17.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
199
+ "language_model.model.layers.17.attention.o_proj.weight": "model-00001-of-00002.safetensors",
200
+ "language_model.model.layers.17.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
201
+ "language_model.model.layers.17.attention_norm.weight": "model-00001-of-00002.safetensors",
202
+ "language_model.model.layers.17.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
203
+ "language_model.model.layers.17.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
204
+ "language_model.model.layers.17.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
205
+ "language_model.model.layers.17.ffn_norm.weight": "model-00001-of-00002.safetensors",
206
+ "language_model.model.layers.18.attention.A_log_bias": "model-00001-of-00002.safetensors",
207
+ "language_model.model.layers.18.attention.conv1d.bias": "model-00001-of-00002.safetensors",
208
+ "language_model.model.layers.18.attention.conv1d.weight": "model-00001-of-00002.safetensors",
209
+ "language_model.model.layers.18.attention.dt_bias": "model-00001-of-00002.safetensors",
210
+ "language_model.model.layers.18.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
211
+ "language_model.model.layers.18.attention.o_proj.weight": "model-00001-of-00002.safetensors",
212
+ "language_model.model.layers.18.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
213
+ "language_model.model.layers.18.attention_norm.weight": "model-00001-of-00002.safetensors",
214
+ "language_model.model.layers.18.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
215
+ "language_model.model.layers.18.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
216
+ "language_model.model.layers.18.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
217
+ "language_model.model.layers.18.ffn_norm.weight": "model-00001-of-00002.safetensors",
218
+ "language_model.model.layers.19.attention.A_log_bias": "model-00001-of-00002.safetensors",
219
+ "language_model.model.layers.19.attention.conv1d.bias": "model-00001-of-00002.safetensors",
220
+ "language_model.model.layers.19.attention.conv1d.weight": "model-00001-of-00002.safetensors",
221
+ "language_model.model.layers.19.attention.dt_bias": "model-00001-of-00002.safetensors",
222
+ "language_model.model.layers.19.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
223
+ "language_model.model.layers.19.attention.o_proj.weight": "model-00001-of-00002.safetensors",
224
+ "language_model.model.layers.19.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
225
+ "language_model.model.layers.19.attention_norm.weight": "model-00001-of-00002.safetensors",
226
+ "language_model.model.layers.19.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
227
+ "language_model.model.layers.19.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
228
+ "language_model.model.layers.19.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
229
+ "language_model.model.layers.19.ffn_norm.weight": "model-00001-of-00002.safetensors",
230
+ "language_model.model.layers.2.attention.A_log_bias": "model-00001-of-00002.safetensors",
231
+ "language_model.model.layers.2.attention.conv1d.bias": "model-00001-of-00002.safetensors",
232
+ "language_model.model.layers.2.attention.conv1d.weight": "model-00001-of-00002.safetensors",
233
+ "language_model.model.layers.2.attention.dt_bias": "model-00001-of-00002.safetensors",
234
+ "language_model.model.layers.2.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
235
+ "language_model.model.layers.2.attention.o_proj.weight": "model-00001-of-00002.safetensors",
236
+ "language_model.model.layers.2.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
237
+ "language_model.model.layers.2.attention_norm.weight": "model-00001-of-00002.safetensors",
238
+ "language_model.model.layers.2.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
239
+ "language_model.model.layers.2.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
240
+ "language_model.model.layers.2.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
241
+ "language_model.model.layers.2.ffn_norm.weight": "model-00001-of-00002.safetensors",
242
+ "language_model.model.layers.20.attention.wo.weight": "model-00001-of-00002.safetensors",
243
+ "language_model.model.layers.20.attention.wqkv.weight": "model-00001-of-00002.safetensors",
244
+ "language_model.model.layers.20.attention_norm.weight": "model-00001-of-00002.safetensors",
245
+ "language_model.model.layers.20.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
246
+ "language_model.model.layers.20.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
247
+ "language_model.model.layers.20.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
248
+ "language_model.model.layers.20.ffn_norm.weight": "model-00001-of-00002.safetensors",
249
+ "language_model.model.layers.21.attention.A_log_bias": "model-00001-of-00002.safetensors",
250
+ "language_model.model.layers.21.attention.conv1d.bias": "model-00001-of-00002.safetensors",
251
+ "language_model.model.layers.21.attention.conv1d.weight": "model-00001-of-00002.safetensors",
252
+ "language_model.model.layers.21.attention.dt_bias": "model-00001-of-00002.safetensors",
253
+ "language_model.model.layers.21.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
254
+ "language_model.model.layers.21.attention.o_proj.weight": "model-00001-of-00002.safetensors",
255
+ "language_model.model.layers.21.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
256
+ "language_model.model.layers.21.attention_norm.weight": "model-00001-of-00002.safetensors",
257
+ "language_model.model.layers.21.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
258
+ "language_model.model.layers.21.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
259
+ "language_model.model.layers.21.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
260
+ "language_model.model.layers.21.ffn_norm.weight": "model-00001-of-00002.safetensors",
261
+ "language_model.model.layers.22.attention.A_log_bias": "model-00001-of-00002.safetensors",
262
+ "language_model.model.layers.22.attention.conv1d.bias": "model-00001-of-00002.safetensors",
263
+ "language_model.model.layers.22.attention.conv1d.weight": "model-00001-of-00002.safetensors",
264
+ "language_model.model.layers.22.attention.dt_bias": "model-00001-of-00002.safetensors",
265
+ "language_model.model.layers.22.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
266
+ "language_model.model.layers.22.attention.o_proj.weight": "model-00001-of-00002.safetensors",
267
+ "language_model.model.layers.22.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
268
+ "language_model.model.layers.22.attention_norm.weight": "model-00001-of-00002.safetensors",
269
+ "language_model.model.layers.22.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
270
+ "language_model.model.layers.22.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
271
+ "language_model.model.layers.22.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
272
+ "language_model.model.layers.22.ffn_norm.weight": "model-00001-of-00002.safetensors",
273
+ "language_model.model.layers.23.attention.A_log_bias": "model-00001-of-00002.safetensors",
274
+ "language_model.model.layers.23.attention.conv1d.bias": "model-00001-of-00002.safetensors",
275
+ "language_model.model.layers.23.attention.conv1d.weight": "model-00001-of-00002.safetensors",
276
+ "language_model.model.layers.23.attention.dt_bias": "model-00001-of-00002.safetensors",
277
+ "language_model.model.layers.23.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
278
+ "language_model.model.layers.23.attention.o_proj.weight": "model-00001-of-00002.safetensors",
279
+ "language_model.model.layers.23.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
280
+ "language_model.model.layers.23.attention_norm.weight": "model-00002-of-00002.safetensors",
281
+ "language_model.model.layers.23.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
282
+ "language_model.model.layers.23.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
283
+ "language_model.model.layers.23.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
284
+ "language_model.model.layers.23.ffn_norm.weight": "model-00002-of-00002.safetensors",
285
+ "language_model.model.layers.3.attention.A_log_bias": "model-00001-of-00002.safetensors",
286
+ "language_model.model.layers.3.attention.conv1d.bias": "model-00001-of-00002.safetensors",
287
+ "language_model.model.layers.3.attention.conv1d.weight": "model-00001-of-00002.safetensors",
288
+ "language_model.model.layers.3.attention.dt_bias": "model-00001-of-00002.safetensors",
289
+ "language_model.model.layers.3.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
290
+ "language_model.model.layers.3.attention.o_proj.weight": "model-00001-of-00002.safetensors",
291
+ "language_model.model.layers.3.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
292
+ "language_model.model.layers.3.attention_norm.weight": "model-00001-of-00002.safetensors",
293
+ "language_model.model.layers.3.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
294
+ "language_model.model.layers.3.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
295
+ "language_model.model.layers.3.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
296
+ "language_model.model.layers.3.ffn_norm.weight": "model-00001-of-00002.safetensors",
297
+ "language_model.model.layers.4.attention.wo.weight": "model-00001-of-00002.safetensors",
298
+ "language_model.model.layers.4.attention.wqkv.weight": "model-00001-of-00002.safetensors",
299
+ "language_model.model.layers.4.attention_norm.weight": "model-00001-of-00002.safetensors",
300
+ "language_model.model.layers.4.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
301
+ "language_model.model.layers.4.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
302
+ "language_model.model.layers.4.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
303
+ "language_model.model.layers.4.ffn_norm.weight": "model-00001-of-00002.safetensors",
304
+ "language_model.model.layers.5.attention.A_log_bias": "model-00001-of-00002.safetensors",
305
+ "language_model.model.layers.5.attention.conv1d.bias": "model-00001-of-00002.safetensors",
306
+ "language_model.model.layers.5.attention.conv1d.weight": "model-00001-of-00002.safetensors",
307
+ "language_model.model.layers.5.attention.dt_bias": "model-00001-of-00002.safetensors",
308
+ "language_model.model.layers.5.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
309
+ "language_model.model.layers.5.attention.o_proj.weight": "model-00001-of-00002.safetensors",
310
+ "language_model.model.layers.5.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
311
+ "language_model.model.layers.5.attention_norm.weight": "model-00001-of-00002.safetensors",
312
+ "language_model.model.layers.5.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
313
+ "language_model.model.layers.5.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
314
+ "language_model.model.layers.5.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
315
+ "language_model.model.layers.5.ffn_norm.weight": "model-00001-of-00002.safetensors",
316
+ "language_model.model.layers.6.attention.A_log_bias": "model-00001-of-00002.safetensors",
317
+ "language_model.model.layers.6.attention.conv1d.bias": "model-00001-of-00002.safetensors",
318
+ "language_model.model.layers.6.attention.conv1d.weight": "model-00001-of-00002.safetensors",
319
+ "language_model.model.layers.6.attention.dt_bias": "model-00001-of-00002.safetensors",
320
+ "language_model.model.layers.6.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
321
+ "language_model.model.layers.6.attention.o_proj.weight": "model-00001-of-00002.safetensors",
322
+ "language_model.model.layers.6.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
323
+ "language_model.model.layers.6.attention_norm.weight": "model-00001-of-00002.safetensors",
324
+ "language_model.model.layers.6.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
325
+ "language_model.model.layers.6.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
326
+ "language_model.model.layers.6.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
327
+ "language_model.model.layers.6.ffn_norm.weight": "model-00001-of-00002.safetensors",
328
+ "language_model.model.layers.7.attention.A_log_bias": "model-00001-of-00002.safetensors",
329
+ "language_model.model.layers.7.attention.conv1d.bias": "model-00001-of-00002.safetensors",
330
+ "language_model.model.layers.7.attention.conv1d.weight": "model-00001-of-00002.safetensors",
331
+ "language_model.model.layers.7.attention.dt_bias": "model-00001-of-00002.safetensors",
332
+ "language_model.model.layers.7.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
333
+ "language_model.model.layers.7.attention.o_proj.weight": "model-00001-of-00002.safetensors",
334
+ "language_model.model.layers.7.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
335
+ "language_model.model.layers.7.attention_norm.weight": "model-00001-of-00002.safetensors",
336
+ "language_model.model.layers.7.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
337
+ "language_model.model.layers.7.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
338
+ "language_model.model.layers.7.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
339
+ "language_model.model.layers.7.ffn_norm.weight": "model-00001-of-00002.safetensors",
340
+ "language_model.model.layers.8.attention.wo.weight": "model-00001-of-00002.safetensors",
341
+ "language_model.model.layers.8.attention.wqkv.weight": "model-00001-of-00002.safetensors",
342
+ "language_model.model.layers.8.attention_norm.weight": "model-00001-of-00002.safetensors",
343
+ "language_model.model.layers.8.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
344
+ "language_model.model.layers.8.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
345
+ "language_model.model.layers.8.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
346
+ "language_model.model.layers.8.ffn_norm.weight": "model-00001-of-00002.safetensors",
347
+ "language_model.model.layers.9.attention.A_log_bias": "model-00001-of-00002.safetensors",
348
+ "language_model.model.layers.9.attention.conv1d.bias": "model-00001-of-00002.safetensors",
349
+ "language_model.model.layers.9.attention.conv1d.weight": "model-00001-of-00002.safetensors",
350
+ "language_model.model.layers.9.attention.dt_bias": "model-00001-of-00002.safetensors",
351
+ "language_model.model.layers.9.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
352
+ "language_model.model.layers.9.attention.o_proj.weight": "model-00001-of-00002.safetensors",
353
+ "language_model.model.layers.9.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
354
+ "language_model.model.layers.9.attention_norm.weight": "model-00001-of-00002.safetensors",
355
+ "language_model.model.layers.9.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
356
+ "language_model.model.layers.9.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
357
+ "language_model.model.layers.9.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
358
+ "language_model.model.layers.9.ffn_norm.weight": "model-00001-of-00002.safetensors",
359
+ "language_model.model.norm.weight": "model-00002-of-00002.safetensors",
360
+ "language_model.model.tok_embeddings.weight": "model-00001-of-00002.safetensors",
361
+ "language_model.output.weight": "model-00002-of-00002.safetensors"
362
+ }
363
+ }
modeling_mmMamba.py ADDED
@@ -0,0 +1,1224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The mmMamba 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
+ import math
17
+ import queue
18
+ import threading
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from einops import rearrange
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
30
+ CausalLMOutputWithPast,
31
+ SequenceClassifierOutputWithPast)
32
+ from transformers.modeling_utils import PreTrainedModel
33
+ from transformers.utils import (add_start_docstrings,
34
+ add_start_docstrings_to_model_forward, logging,
35
+ replace_return_docstrings)
36
+ from fla.modules import FusedRMSNormSwishGate, RMSNorm, ShortConvolution
37
+ import copy
38
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
39
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
40
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
41
+ from transformers.cache_utils import Cache
42
+ import time
43
+
44
+ try:
45
+ from transformers.generation.streamers import BaseStreamer
46
+ except: # noqa # pylint: disable=bare-except
47
+ BaseStreamer = None
48
+
49
+ from .configuration_mmMamba import mmMambaConfig
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CONFIG_FOR_DOC = 'mmMambaConfig'
54
+
55
+ flash_attn_func, flash_attn_varlen_func = None, None
56
+ pad_input, index_first_axis, unpad_input = None, None, None
57
+ try:
58
+ from flash_attn import flash_attn_func as _flash_attn_func
59
+ from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis as _index_first_axis
61
+ from flash_attn.bert_padding import pad_input as _pad_input
62
+ from flash_attn.bert_padding import unpad_input as _unpad_input
63
+
64
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
65
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
66
+ has_flash_attn = True
67
+ except:
68
+ has_flash_attn = False
69
+
70
+ try:
71
+ from flash_attn import flash_attn_with_kvcache
72
+ except ImportError:
73
+ flash_attn_with_kvcache = None
74
+
75
+ try:
76
+ from flash_attn.layers.rotary import RotaryEmbedding
77
+ except ImportError:
78
+ RotaryEmbedding = None
79
+
80
+ import torch.nn.functional as F
81
+
82
+ def _update_kv_cache(kv, inference_params, layer_idx):
83
+ """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)"""
84
+ # Pre-allocate memory for key-values for inference.
85
+ num_heads, head_dim = kv.shape[-2:]
86
+ assert layer_idx in inference_params.key_value_memory_dict
87
+ kv_cache, _ = inference_params.key_value_memory_dict[layer_idx]
88
+ # Adjust key and value for inference
89
+ batch_start = inference_params.batch_size_offset
90
+ batch_end = batch_start + kv.shape[0]
91
+ sequence_start = inference_params.seqlen_offset
92
+ sequence_end = sequence_start + kv.shape[1]
93
+ assert batch_end <= kv_cache.shape[0]
94
+ assert sequence_end <= kv_cache.shape[1]
95
+ assert kv_cache is not None
96
+ kv_cache[batch_start:batch_end, sequence_start:sequence_end, ...] = kv
97
+ return kv_cache[batch_start:batch_end, :sequence_end, ...]
98
+
99
+ def _import_flash_attn():
100
+ global flash_attn_func, flash_attn_varlen_func
101
+ global pad_input, index_first_axis, unpad_input
102
+ try:
103
+ from flash_attn import flash_attn_func as _flash_attn_func
104
+ from flash_attn import \
105
+ flash_attn_varlen_func as _flash_attn_varlen_func
106
+ from flash_attn.bert_padding import \
107
+ index_first_axis as _index_first_axis
108
+ from flash_attn.bert_padding import pad_input as _pad_input
109
+ from flash_attn.bert_padding import unpad_input as _unpad_input
110
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
111
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
112
+ except ImportError:
113
+ raise ImportError('flash_attn is not installed.')
114
+
115
+
116
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->mmMamba
117
+ class mmMambaRMSNorm(nn.Module):
118
+ def __init__(self, hidden_size, eps=1e-6):
119
+ """
120
+ mmMambaRMSNorm is equivalent to T5LayerNorm
121
+ """
122
+ super().__init__()
123
+ self.weight = nn.Parameter(torch.ones(hidden_size))
124
+ self.variance_epsilon = eps
125
+
126
+ def forward(self, hidden_states):
127
+ input_dtype = hidden_states.dtype
128
+ hidden_states = hidden_states.to(torch.float32)
129
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
130
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
131
+ return self.weight * hidden_states.to(input_dtype)
132
+
133
+
134
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->mmMamba
135
+ class mmMambaRotaryEmbedding(nn.Module):
136
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
137
+ super().__init__()
138
+
139
+ self.dim = dim
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.base = base
142
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
143
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
144
+
145
+ # Build here to make `torch.jit.trace` work.
146
+ self._set_cos_sin_cache(
147
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
148
+ )
149
+
150
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
151
+ self.max_seq_len_cached = seq_len
152
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
153
+
154
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
155
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
156
+ emb = torch.cat((freqs, freqs), dim=-1)
157
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
158
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
159
+
160
+ def forward(self, x, seq_len=None):
161
+ # x: [bs, num_attention_heads, seq_len, head_size]
162
+ if seq_len > self.max_seq_len_cached:
163
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
164
+
165
+ return (
166
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
167
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
168
+ )
169
+
170
+
171
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->mmMamba
172
+ class mmMambaLinearScalingRotaryEmbedding(mmMambaRotaryEmbedding):
173
+ """mmMambaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
174
+
175
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
176
+ self.scaling_factor = scaling_factor
177
+ super().__init__(dim, max_position_embeddings, base, device)
178
+
179
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
180
+ self.max_seq_len_cached = seq_len
181
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
182
+ t = t / self.scaling_factor
183
+
184
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
185
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
186
+ emb = torch.cat((freqs, freqs), dim=-1)
187
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
188
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
189
+
190
+
191
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->mmMamba
192
+ class mmMambaDynamicNTKScalingRotaryEmbedding(mmMambaRotaryEmbedding):
193
+ """mmMambaRotaryEmbedding extended with Dynamic NTK scaling.
194
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
195
+ """
196
+
197
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
198
+ self.scaling_factor = scaling_factor
199
+ super().__init__(dim, max_position_embeddings, base, device)
200
+
201
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
202
+ self.max_seq_len_cached = seq_len
203
+
204
+ if seq_len > self.max_position_embeddings:
205
+ base = self.base * (
206
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
207
+ ) ** (self.dim / (self.dim - 2))
208
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
209
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
210
+
211
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
212
+
213
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
214
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
215
+ emb = torch.cat((freqs, freqs), dim=-1)
216
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
217
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
218
+
219
+
220
+
221
+ class mmMambaMLP(nn.Module):
222
+ def __init__(self, config):
223
+ super().__init__()
224
+ self.config = config
225
+ self.hidden_size = config.hidden_size
226
+ self.intermediate_size = config.intermediate_size
227
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
228
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
229
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
230
+ self.act_fn = ACT2FN[config.hidden_act]
231
+
232
+ def forward(self, x):
233
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
234
+
235
+ return down_proj
236
+
237
+
238
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
239
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
240
+ """
241
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
242
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
243
+ """
244
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
245
+ if n_rep == 1:
246
+ return hidden_states
247
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
248
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
249
+
250
+ def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
251
+ """
252
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
253
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
254
+ """
255
+ batch, num_key_value_heads, head_dim = hidden_states.shape
256
+ if n_rep == 1:
257
+ return hidden_states
258
+ hidden_states = hidden_states[:, :, None, :].expand(batch, num_key_value_heads, n_rep, head_dim)
259
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, head_dim)
260
+
261
+
262
+ class MHA_LM(nn.Module):
263
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
264
+
265
+ def __init__(self, config: mmMambaConfig, layer_idx: int):
266
+ super().__init__()
267
+ self.config = config
268
+ self.layer_idx = layer_idx#-------------------------
269
+ self.hidden_size = config.hidden_size
270
+ self.num_heads = config.num_attention_heads
271
+ self.head_dim = self.hidden_size // self.num_heads
272
+ self.num_key_value_heads = config.num_key_value_heads
273
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
274
+ self.max_position_embeddings = config.max_position_embeddings
275
+ self.is_causal = True
276
+ self.rotary_emb_dim = self.head_dim
277
+ self.softmax_scale = None
278
+ self.causal = True
279
+
280
+ if (self.head_dim * self.num_heads) != self.hidden_size:
281
+ raise ValueError(
282
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
283
+ f" and `num_heads`: {self.num_heads})."
284
+ )
285
+
286
+ self.wqkv = nn.Linear(
287
+ self.hidden_size,
288
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
289
+ bias=False,
290
+ )
291
+
292
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
293
+ self.rotary_emb = RotaryEmbedding(
294
+ self.head_dim,
295
+ base=self.config.rope_theta,
296
+ interleaved=False,
297
+ device=self.wo.weight.device,
298
+ )
299
+
300
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
301
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
302
+
303
+ def _update_kv_cache(self, kv, inference_params):
304
+ """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)"""
305
+ assert self.layer_idx is not None, "Generation requires layer_idx in the constructor"
306
+ return _update_kv_cache(kv, inference_params, self.layer_idx)
307
+
308
+ def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params):
309
+ """
310
+ Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention.
311
+ q: (batch_size, seqlen_q, nheads, head_dim)
312
+ kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim)
313
+ """
314
+ assert inference_params is not None and inference_params.seqlen_offset > 0
315
+ if self.rotary_emb_dim > 0:
316
+ self.rotary_emb._update_cos_sin_cache(
317
+ inference_params.max_seqlen, device=q.device, dtype=q.dtype
318
+ )
319
+ rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached
320
+ else:
321
+ rotary_cos, rotary_sin = None, None
322
+ batch = q.shape[0]
323
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
324
+ kv_cache = kv_cache[:batch]
325
+ cache_seqlens = (
326
+ inference_params.lengths_per_sample[:batch]
327
+ if inference_params.lengths_per_sample is not None
328
+ else inference_params.seqlen_offset
329
+ )
330
+ assert flash_attn_with_kvcache is not None, "flash_attn must be installed"
331
+ context = flash_attn_with_kvcache(
332
+ q,
333
+ kv_cache[:, :, 0],
334
+ kv_cache[:, :, 1],
335
+ kv[:, :, 0],
336
+ kv[:, :, 1],
337
+ rotary_cos=rotary_cos,
338
+ rotary_sin=rotary_sin,
339
+ cache_seqlens=cache_seqlens,
340
+ softmax_scale=self.softmax_scale,
341
+ causal=self.causal,
342
+ rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False,
343
+ )
344
+ return context
345
+
346
+ def _update_kvcache_attention(self, q, kv, inference_params):
347
+ """Write kv to inference_params, then do attention"""
348
+ if (
349
+ inference_params.seqlen_offset == 0
350
+ or flash_attn_with_kvcache is None
351
+ ):
352
+ # TODO: this only uses seqlen_offset and not lengths_per_sample.
353
+ kv = self._update_kv_cache(kv, inference_params)
354
+ k, v = kv.unbind(dim=-3)
355
+ #k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
356
+ #v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
357
+ attn_output = flash_attn_func(
358
+ q, k, v, 0.0, softmax_scale=None, causal=self.causal
359
+ )
360
+ return attn_output
361
+ else:
362
+ batch = q.shape[0]
363
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
364
+ kv_cache = kv_cache[:batch]
365
+ cache_seqlens = (
366
+ inference_params.lengths_per_sample[:batch]
367
+ if inference_params.lengths_per_sample is not None
368
+ else inference_params.seqlen_offset
369
+ )
370
+ return flash_attn_with_kvcache(
371
+ q,
372
+ kv_cache[:, :, 0],
373
+ kv_cache[:, :, 1],
374
+ kv[:, :, 0],
375
+ kv[:, :, 1],
376
+ cache_seqlens=cache_seqlens,
377
+ softmax_scale=self.softmax_scale,
378
+ causal=self.causal,
379
+ )
380
+
381
+ def forward(
382
+ self,
383
+ hidden_states: torch.Tensor,
384
+ inference_params = None,
385
+ output_attentions: bool = False,
386
+ cache_position: Optional[torch.LongTensor] = None,#------------------------------------------------------------------------
387
+ use_cache: bool = False,
388
+ **kwargs,
389
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
390
+ if inference_params is not None and self.layer_idx not in inference_params.key_value_memory_dict:
391
+ inference_params.key_value_memory_dict[self.layer_idx] = self.allocate_inference_cache(
392
+ hidden_states.shape[0], inference_params.max_seqlen, dtype=hidden_states.dtype
393
+ )
394
+ seqlen_offset = (
395
+ 0
396
+ if inference_params is None
397
+ else (
398
+ inference_params.lengths_per_sample
399
+ if inference_params.lengths_per_sample is not None
400
+ else inference_params.seqlen_offset
401
+ )
402
+ )
403
+
404
+ bsz, q_len, _ = hidden_states.size()
405
+ rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None
406
+
407
+ qkv = self.wqkv(hidden_states)
408
+ qkv = rearrange(
409
+ qkv,
410
+ "b q (h gs d) -> b q h gs d",
411
+ gs=2 + self.num_key_value_groups,
412
+ d=self.head_dim,
413
+ )
414
+
415
+ q = qkv[..., : self.num_key_value_groups, :]
416
+ q = rearrange(q, "b q h gs d -> b q (h gs) d")
417
+ kv = qkv[..., self.num_key_value_groups:, :].transpose(2,3)
418
+
419
+ if (
420
+ inference_params is None
421
+ or inference_params.seqlen_offset == 0
422
+ or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0)
423
+ ):
424
+ if self.rotary_emb_dim > 0:
425
+ q, kv = self.rotary_emb(
426
+ q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen
427
+ )
428
+ if inference_params is None:
429
+ k, v = kv.unbind(dim=-3)
430
+ k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
431
+ v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
432
+ context = F.scaled_dot_product_attention(
433
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, scale=None
434
+ ).transpose(1, 2)
435
+ else:
436
+ context = self._update_kvcache_attention(q, kv, inference_params)
437
+ else:
438
+ context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params)
439
+ context = rearrange(context, "... h d -> ... (h d)")
440
+ out = self.wo(context)
441
+ return out
442
+
443
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None):
444
+ dtype = self.wo.weight.dtype if dtype is None else dtype
445
+ device = self.wo.weight.device
446
+ kv_cache = torch.empty(
447
+ batch_size, max_seqlen, 2, self.num_key_value_heads, self.head_dim, dtype=dtype, device=device,
448
+ )
449
+ return kv_cache, None
450
+
451
+
452
+ class Mamba2_LM(nn.Module):
453
+ """
454
+ LoLCATs attention implementation initialized from a
455
+ `LlamaAttention` or `MistralAttention` object (base_attn)
456
+
457
+ Most of the arguments are directly tied to argparse args
458
+ - For now we don't support padding.
459
+ """
460
+ def __init__(self, config: mmMambaConfig, layer_idx: Optional[int] = None,
461
+ elementwise_affine: Optional[bool] = True,
462
+ norm_eps: float = 1e-5,
463
+ ):
464
+ super().__init__()
465
+ self.config = config
466
+ self.hidden_size = config.hidden_size
467
+ self.num_heads = config.num_attention_heads
468
+ self.head_dim = self.hidden_size // self.num_heads
469
+ self.num_key_value_heads = config.num_key_value_heads
470
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
471
+ self.max_position_embeddings = config.max_position_embeddings
472
+ self.layer_idx = layer_idx
473
+ self.bias = False
474
+ self.chunk_size = 128
475
+ conv_bias = True
476
+ self.conv_bias = conv_bias
477
+ self.d_conv = 2
478
+ self.activation="silu"
479
+ self.max_position_embeddings = config.max_position_embeddings
480
+ self.rope_theta = config.rope_theta
481
+
482
+ self.wvkqgdt = nn.Linear(
483
+ self.hidden_size,
484
+ (self.num_heads + 2 * self.num_key_value_heads + self.num_heads) * self.head_dim + self.num_heads,
485
+ bias=self.bias
486
+ )
487
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
488
+
489
+ self.device = self.wvkqgdt.weight.device
490
+ self.dtype = self.wvkqgdt.weight.dtype
491
+
492
+ conv_dim = self.num_heads * self.head_dim + 2 * self.num_key_value_heads * self.head_dim
493
+
494
+ self.conv1d = nn.Conv1d(
495
+ in_channels=conv_dim,
496
+ out_channels=conv_dim,
497
+ bias=self.conv_bias,
498
+ kernel_size=self.d_conv,
499
+ groups=conv_dim,
500
+ padding=self.d_conv - 1,
501
+ device=self.device,
502
+ dtype=self.dtype
503
+ )
504
+ with torch.no_grad():
505
+ self.conv1d.weight.zero_()
506
+ self.conv1d.weight[:, 0, 1] = 1
507
+ self.conv1d.bias.zero_()
508
+
509
+ # Activation after conv
510
+ if self.activation == "identity":
511
+ self.act = nn.Identity()
512
+ elif self.activation in ["silu", "swish"]:
513
+ self.act = nn.SiLU()
514
+ else:
515
+ raise ValueError(f"Unknown activation {self.activation}")
516
+
517
+ self.g_norm_swish_gate = FusedRMSNormSwishGate(hidden_size=self.head_dim, elementwise_affine=elementwise_affine, eps=norm_eps).to(self.dtype).to(self.device)
518
+
519
+ dt = torch.exp(
520
+ torch.rand(self.num_heads, dtype=self.dtype, device=self.device) * (math.log(0.1) - math.log(0.001))
521
+ + math.log(0.001)
522
+ )
523
+ dt = torch.clamp(dt, min=0.001)
524
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
525
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
526
+ self.dt_bias = nn.Parameter(inv_dt)
527
+ self.dt_bias._no_weight_decay = True
528
+
529
+ A_log_bias = torch.zeros(self.num_heads, dtype=self.dtype, device=self.device)
530
+ self.A_log_bias = nn.Parameter(A_log_bias)
531
+ self.A_log_bias._no_weight_decay = True
532
+
533
+ def forward(self,
534
+ hidden_states: torch.Tensor,
535
+ inference_params = None,
536
+ output_attentions: bool = False,
537
+ use_cache: bool = True,
538
+ **kwargs,
539
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
540
+ hidden_states = hidden_states.to(self.dtype)
541
+ vkqgdt = self.wvkqgdt(hidden_states)
542
+ vkq, g, dt = torch.split(
543
+ vkqgdt,
544
+ [
545
+ (2*self.num_key_value_heads+self.num_heads) * self.head_dim,
546
+ self.num_heads * self.head_dim,
547
+ self.num_heads,
548
+ ],
549
+ dim=2,
550
+ )
551
+ batch, seqlen, _ = hidden_states.shape
552
+ conv_state, ssm_state = None, None
553
+ if inference_params is not None:
554
+ conv_state, ssm_state = self._get_states_from_cache(inference_params, batch)
555
+
556
+ if use_cache and inference_params.seqlen_offset==0:
557
+ vkq, new_conv_states = causal_conv1d_fn(
558
+ vkq.transpose(1, 2),
559
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
560
+ self.conv1d.bias,
561
+ initial_states=None,
562
+ return_final_states=True,
563
+ activation=None if self.activation == "identity" else self.activation,
564
+ )
565
+
566
+ v, k, q = torch.split(
567
+ vkq,
568
+ [
569
+ self.num_key_value_heads * self.head_dim,
570
+ self.num_key_value_heads * self.head_dim,
571
+ self.num_heads * self.head_dim,
572
+ ],
573
+ dim=1,
574
+ )
575
+
576
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
577
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
578
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
579
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
580
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
581
+
582
+ A = -torch.exp(self.A_log_bias.float())
583
+
584
+ y, new_ssm_states = mamba_chunk_scan_combined(
585
+ x = v,
586
+ #x = v / F.softplus(A_log).to(v.dtype).unsqueeze(-1),
587
+ dt=dt,
588
+ dt_softplus=True,
589
+ A=A,
590
+ B=k,
591
+ C=q,
592
+ chunk_size=self.chunk_size,
593
+ dt_bias=self.dt_bias,
594
+ initial_states=None, # currently not supported by mamba_ssm.utils.generation
595
+ return_final_states=True,
596
+ )
597
+
598
+ conv_state.copy_(new_conv_states)
599
+ ssm_state.copy_(new_ssm_states)
600
+
601
+ elif use_cache and inference_params.seqlen_offset>0:
602
+
603
+ vkq = causal_conv1d_update(
604
+ vkq.transpose(1, 2).squeeze(-1),
605
+ conv_state,
606
+ self.conv1d.weight.squeeze(1),
607
+ self.conv1d.bias,
608
+ self.activation,
609
+ )
610
+
611
+ v, k, q = torch.split(
612
+ vkq,
613
+ [
614
+ self.num_key_value_heads * self.head_dim,
615
+ self.num_key_value_heads * self.head_dim,
616
+ self.num_heads * self.head_dim,
617
+ ],
618
+ dim=1,
619
+ )
620
+
621
+ v = rearrange(v, "b (h n) -> b h n", h=self.num_key_value_heads)
622
+ k = rearrange(k, "b (h n) -> b h n", h=self.num_key_value_heads)
623
+ q = rearrange(q, "b (h n) -> b h n", h=self.num_heads)
624
+ k = repeat_kv2(k, self.num_key_value_groups)
625
+ v = repeat_kv2(v, self.num_key_value_groups)
626
+
627
+ dt = dt.transpose(1, 2).squeeze(-1)
628
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
629
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
630
+ A = -torch.exp(self.A_log_bias.float())
631
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.head_dim).to(dtype=torch.float32)
632
+ D = torch.zeros((self.num_heads, self.head_dim), dtype=A.dtype, device=A.device)
633
+
634
+ y = selective_state_update(
635
+ ssm_state,
636
+ v,
637
+ dt,
638
+ A=A,
639
+ B=k,
640
+ C=q,
641
+ D=D,
642
+ dt_bias=dt_bias,
643
+ dt_softplus=True,
644
+ )
645
+
646
+ else:
647
+ vkq = causal_conv1d_fn(
648
+ vkq.transpose(1, 2),
649
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
650
+ self.conv1d.bias,
651
+ initial_states=None,
652
+ return_final_states=False,
653
+ activation=None if self.activation == "identity" else self.activation,
654
+ )
655
+
656
+ v, k, q = torch.split(
657
+ vkq,
658
+ [
659
+ self.num_key_value_heads * self.head_dim,
660
+ self.num_key_value_heads * self.head_dim,
661
+ self.num_heads * self.head_dim,
662
+ ],
663
+ dim=1,
664
+ )
665
+
666
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
667
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
668
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
669
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
670
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
671
+
672
+ A = -torch.exp(self.A_log_bias.float())
673
+
674
+ y = mamba_chunk_scan_combined(
675
+ x = v,
676
+ dt=dt,
677
+ dt_softplus=True,
678
+ A=A,
679
+ B=k,
680
+ C=q,
681
+ chunk_size=self.chunk_size,
682
+ dt_bias=self.dt_bias,
683
+ initial_states=None, # currently not supported by mamba_ssm.utils.generation
684
+ return_final_states=False,
685
+ )
686
+
687
+ g = rearrange(g, 'b l (h d) -> b l h d', h=self.num_heads)
688
+ y_true = self.g_norm_swish_gate(y, g)
689
+ y_true = y_true.view(batch, seqlen, self.hidden_size)
690
+ y_true = self.o_proj(y_true)
691
+
692
+ return y_true
693
+
694
+ def _get_states_from_cache(self, inference_params, batch_size, initialize_states=False):
695
+ device = self.conv1d.weight.device
696
+ dtype = self.conv1d.weight.dtype
697
+ assert self.layer_idx is not None
698
+ if self.layer_idx not in inference_params.key_value_memory_dict:
699
+ batch_shape = (batch_size,)
700
+ conv_state = torch.zeros(
701
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
702
+ )
703
+ ssm_state = torch.zeros(
704
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
705
+ )
706
+ inference_params.key_value_memory_dict[self.layer_idx] = (conv_state, ssm_state)
707
+ else:
708
+ conv_state, ssm_state = inference_params.key_value_memory_dict[self.layer_idx]
709
+ # TODO: What if batch size changes between generation, and we reuse the same states?
710
+ if initialize_states:
711
+ conv_state.zero_()
712
+ ssm_state.zero_()
713
+ return conv_state, ssm_state
714
+
715
+
716
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
717
+ device = self.conv1d.weight.device
718
+ dtype = self.conv1d.weight.dtype
719
+ conv_state = torch.zeros(
720
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
721
+ )
722
+
723
+ ssm_state = torch.zeros(
724
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
725
+ )
726
+ return conv_state, ssm_state
727
+
728
+
729
+ mmMamba_ATTENTION_CLASSES = {
730
+ 'mha': MHA_LM,
731
+ "mamba2":Mamba2_LM
732
+ }
733
+
734
+
735
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
736
+ class mmMambaDecoderLayer(nn.Module):
737
+ def __init__(self, config: mmMambaConfig, layer_idx: int):
738
+ super().__init__()
739
+ self.hidden_size = config.hidden_size
740
+ self.layer_idx = layer_idx
741
+ self.attention = mmMamba_ATTENTION_CLASSES[config.layers_block_type[layer_idx-8]](config=config, layer_idx=layer_idx)
742
+
743
+ self.feed_forward = mmMambaMLP(config)
744
+ self.attention_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
745
+ self.ffn_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
746
+
747
+
748
+ def forward(
749
+ self,
750
+ hidden_states: torch.Tensor,
751
+ inference_params = None,
752
+ output_attentions: Optional[bool] = False,
753
+ use_cache: Optional[bool] = True,
754
+ **kwargs,
755
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
756
+ """
757
+ Args:
758
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
759
+ output_attentions (`bool`, *optional*):
760
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
761
+ returned tensors for more detail.
762
+ use_cache (`bool`, *optional*):
763
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
764
+ (see `past_key_values`).
765
+ """
766
+ #start_time = time.time()
767
+ residual = hidden_states
768
+
769
+ hidden_states = self.attention_norm(hidden_states)
770
+
771
+ # Self Attention
772
+ hidden_states = self.attention(
773
+ hidden_states=hidden_states,
774
+ inference_params=inference_params,
775
+ output_attentions=output_attentions,
776
+ use_cache=use_cache,
777
+ **kwargs,
778
+ )
779
+ hidden_states = residual + hidden_states
780
+
781
+ # Fully Connected
782
+ residual = hidden_states
783
+ hidden_states = self.ffn_norm(hidden_states)
784
+ hidden_states = self.feed_forward(hidden_states)
785
+ hidden_states = residual + hidden_states
786
+
787
+
788
+ outputs = (hidden_states,)
789
+
790
+ if output_attentions:
791
+ outputs += self_attn_weights
792
+
793
+ #end_time = time.time()
794
+ #print("language_model_time:", end_time-start_time)
795
+ return outputs
796
+
797
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
798
+ return self.attention.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
799
+
800
+
801
+ mmMamba_START_DOCSTRING = r"""
802
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
803
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
804
+ etc.)
805
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
806
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
807
+ and behavior.
808
+ Parameters:
809
+ config ([`mmMambaConfig`]):
810
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
811
+ load the weights associated with the model, only the configuration. Check out the
812
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
813
+ """
814
+
815
+
816
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->mmMamba
817
+ @add_start_docstrings(
818
+ 'The bare mmMamba Model outputting raw hidden-states without any specific head on top.',
819
+ mmMamba_START_DOCSTRING,
820
+ )
821
+ class mmMambaPreTrainedModel(PreTrainedModel):
822
+ config_class = mmMambaConfig
823
+ base_model_prefix = 'model'
824
+ supports_gradient_checkpointing = True
825
+ _no_split_modules = ['mmMambaDecoderLayer']
826
+ _skip_keys_device_placement = 'past_key_values'
827
+ _supports_flash_attn_2 = True
828
+
829
+ def _init_weights(self, module):
830
+ std = self.config.initializer_range
831
+ if isinstance(module, nn.Linear):
832
+ module.weight.data.normal_(mean=0.0, std=std)
833
+ if module.bias is not None:
834
+ module.bias.data.zero_()
835
+ elif isinstance(module, nn.Embedding):
836
+ module.weight.data.normal_(mean=0.0, std=std)
837
+ if module.padding_idx is not None:
838
+ module.weight.data[module.padding_idx].zero_()
839
+
840
+
841
+ mmMamba_INPUTS_DOCSTRING = r"""
842
+ Args:
843
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
844
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
845
+ it.
846
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
847
+ [`PreTrainedTokenizer.__call__`] for details.
848
+ [What are input IDs?](../glossary#input-ids)
849
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
850
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
851
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
852
+ model's internal embedding lookup matrix.
853
+ use_cache (`bool`, *optional*):
854
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
855
+ `past_key_values`).
856
+ output_attentions (`bool`, *optional*):
857
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
858
+ tensors for more detail.
859
+ output_hidden_states (`bool`, *optional*):
860
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
861
+ more detail.
862
+ return_dict (`bool`, *optional*):
863
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
864
+ """
865
+
866
+
867
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
868
+ @add_start_docstrings(
869
+ 'The bare mmMamba Model outputting raw hidden-states without any specific head on top.',
870
+ mmMamba_START_DOCSTRING,
871
+ )
872
+ class mmMambaModel(mmMambaPreTrainedModel):
873
+ """
874
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`mmMambaDecoderLayer`]
875
+ Args:
876
+ config: mmMambaConfig
877
+ """
878
+
879
+ _auto_class = 'AutoModel'
880
+
881
+ def __init__(self, config: mmMambaConfig):
882
+ super().__init__(config)
883
+ self.padding_idx = config.pad_token_id
884
+ self.vocab_size = config.vocab_size
885
+ self.config = config
886
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
887
+
888
+ self.layers = nn.ModuleList([mmMambaDecoderLayer(config, (layer_idx+8)) for layer_idx in range(config.num_hidden_layers)])
889
+ self.norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
890
+
891
+ self.gradient_checkpointing = False
892
+ # Initialize weights and apply final processing
893
+ self.post_init()
894
+
895
+ def get_input_embeddings(self):
896
+ return self.tok_embeddings
897
+
898
+ def set_input_embeddings(self, value):
899
+ self.tok_embeddings = value
900
+
901
+ @add_start_docstrings_to_model_forward(mmMamba_INPUTS_DOCSTRING)
902
+ def forward(
903
+ self,
904
+ input_ids: torch.LongTensor = None,
905
+ inference_params=None,
906
+ inputs_embeds: Optional[torch.FloatTensor] = None,
907
+ use_cache: Optional[bool] = True,
908
+ output_attentions: Optional[bool] = None,
909
+ output_hidden_states: Optional[bool] = None,
910
+ return_dict: Optional[bool] = None,
911
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
912
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
913
+ output_hidden_states = (
914
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
915
+ )
916
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
917
+
918
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
919
+
920
+ if self.config.attn_implementation == 'flash_attention_2':
921
+ _import_flash_attn()
922
+
923
+ # retrieve input_ids and inputs_embeds
924
+ if input_ids is not None and inputs_embeds is not None:
925
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
926
+ elif input_ids is not None:
927
+ batch_size, seq_length = input_ids.shape[:2]
928
+ elif inputs_embeds is not None:
929
+ batch_size, seq_length = inputs_embeds.shape[:2]
930
+ else:
931
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
932
+
933
+ if inputs_embeds is None:
934
+ inputs_embeds = self.tok_embeddings(input_ids)
935
+
936
+ # embed positions
937
+ hidden_states = inputs_embeds
938
+
939
+ if self.gradient_checkpointing and self.training:
940
+ if use_cache:
941
+ logger.warning_once(
942
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
943
+ )
944
+ use_cache = False
945
+
946
+ # decoder layers
947
+ all_hidden_states = () if output_hidden_states else None
948
+ all_self_attns = () if output_attentions else None
949
+ next_decoder_cache = () if use_cache else None
950
+
951
+ for idx, decoder_layer in enumerate(self.layers):
952
+ if output_hidden_states:
953
+ all_hidden_states += (hidden_states,)
954
+
955
+ if self.gradient_checkpointing and self.training:
956
+
957
+ def create_custom_forward(module):
958
+ def custom_forward(*inputs):
959
+ # None for past_key_value
960
+ return module(*inputs, output_attentions, None)
961
+
962
+ return custom_forward
963
+
964
+ layer_outputs = torch.utils.checkpoint.checkpoint(
965
+ create_custom_forward(decoder_layer),
966
+ hidden_states,
967
+ inference_params,
968
+ None,
969
+ )
970
+ else:
971
+ layer_outputs = decoder_layer(
972
+ hidden_states,
973
+ inference_params=inference_params,
974
+ output_attentions=output_attentions,
975
+ use_cache=use_cache,
976
+ )
977
+
978
+ hidden_states = layer_outputs[0]
979
+
980
+
981
+ if output_attentions:
982
+ all_self_attns += layer_outputs[1]
983
+
984
+ hidden_states = self.norm(hidden_states)
985
+
986
+ # add hidden states from the last decoder layer
987
+ if output_hidden_states:
988
+ all_hidden_states += (hidden_states,)
989
+
990
+ next_cache = None
991
+ if not return_dict:
992
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
993
+ return BaseModelOutputWithPast(
994
+ last_hidden_state=hidden_states,
995
+ past_key_values=next_cache,
996
+ hidden_states=all_hidden_states,
997
+ attentions=all_self_attns,
998
+ )
999
+
1000
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
1001
+ return {
1002
+ layer.layer_idx: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
1003
+ for layer in self.layers
1004
+ }
1005
+
1006
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
1007
+ class mmMambaForCausalLM(mmMambaPreTrainedModel):
1008
+ _auto_class = 'AutoModelForCausalLM'
1009
+
1010
+ _tied_weights_keys = ['output.weight']
1011
+
1012
+ def __init__(self, config):
1013
+ super().__init__(config)
1014
+ self.model = mmMambaModel(config)
1015
+ self.vocab_size = config.vocab_size
1016
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1017
+
1018
+ # Initialize weights and apply final processing
1019
+ self.post_init()
1020
+
1021
+ def get_input_embeddings(self):
1022
+ return self.model.tok_embeddings
1023
+
1024
+ def set_input_embeddings(self, value):
1025
+ self.model.tok_embeddings = value
1026
+
1027
+ def get_output_embeddings(self):
1028
+ return self.output
1029
+
1030
+ def set_output_embeddings(self, new_embeddings):
1031
+ self.output = new_embeddings
1032
+
1033
+ def set_decoder(self, decoder):
1034
+ self.model = decoder
1035
+
1036
+ def get_decoder(self):
1037
+ return self.model
1038
+
1039
+ @add_start_docstrings_to_model_forward(mmMamba_INPUTS_DOCSTRING)
1040
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1041
+ def forward(
1042
+ self,
1043
+ input_ids: torch.LongTensor = None,
1044
+ inference_params=None,
1045
+ num_last_tokens=0,
1046
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1047
+ labels: Optional[torch.LongTensor] = None,
1048
+ use_cache: Optional[bool] = True,
1049
+ output_attentions: Optional[bool] = None,
1050
+ output_hidden_states: Optional[bool] = None,
1051
+ return_dict: Optional[bool] = None,
1052
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1053
+ r"""
1054
+ Args:
1055
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1056
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1057
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1058
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1059
+ Returns:
1060
+ Example:
1061
+ ```python
1062
+ >>> from transformers import AutoTokenizer, mmMambaForCausalLM
1063
+ >>> model = mmMambaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1064
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1065
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1066
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1067
+ >>> # Generate
1068
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1069
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1070
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1071
+ ```"""
1072
+
1073
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1074
+ output_hidden_states = (
1075
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1076
+ )
1077
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1078
+
1079
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1080
+ outputs = self.model(
1081
+ input_ids=input_ids,
1082
+ inference_params=inference_params,
1083
+ inputs_embeds=inputs_embeds,
1084
+ use_cache=use_cache,
1085
+ output_attentions=output_attentions,
1086
+ output_hidden_states=output_hidden_states,
1087
+ return_dict=return_dict,
1088
+ )
1089
+
1090
+ hidden_states = outputs[0]
1091
+
1092
+ if num_last_tokens > 0:
1093
+ hidden_states = hidden_states[:, -num_last_tokens:]
1094
+
1095
+ logits = self.output(hidden_states)
1096
+ logits = logits.float()
1097
+
1098
+ loss = None
1099
+ if labels is not None:
1100
+ # Shift so that tokens < n predict n
1101
+ shift_logits = logits[..., :-1, :].contiguous()
1102
+ shift_labels = labels[..., 1:].contiguous()
1103
+ # Flatten the tokens
1104
+ loss_fct = CrossEntropyLoss()
1105
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1106
+ shift_labels = shift_labels.view(-1)
1107
+ # Enable model parallelism
1108
+ shift_labels = shift_labels.to(shift_logits.device)
1109
+ loss = loss_fct(shift_logits, shift_labels)
1110
+
1111
+ if not return_dict:
1112
+ output = (logits,) + outputs[1:]
1113
+ return (loss,) + output if loss is not None else output
1114
+
1115
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1116
+ output = CausalLMOutputWithPast(
1117
+ loss=loss,
1118
+ logits=logits,
1119
+ past_key_values=outputs.past_key_values,
1120
+ hidden_states=outputs.hidden_states,
1121
+ attentions=outputs.attentions,
1122
+ )
1123
+ output['logits'] = output['logits'].to(device)
1124
+ return output
1125
+
1126
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
1127
+ return self.model.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
1128
+
1129
+ @staticmethod
1130
+ def _reorder_cache(past_key_values, beam_idx):
1131
+ reordered_past = ()
1132
+ for layer_past in past_key_values:
1133
+ reordered_past += (
1134
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1135
+ )
1136
+ return reordered_past
1137
+
1138
+
1139
+ @torch.no_grad()
1140
+ def stream_chat(
1141
+ self,
1142
+ tokenizer,
1143
+ query: str,
1144
+ history: List[Tuple[str, str]] = [],
1145
+ max_new_tokens: int = 1024,
1146
+ do_sample: bool = True,
1147
+ temperature: float = 0.8,
1148
+ top_p: float = 0.8,
1149
+ **kwargs,
1150
+ ):
1151
+ """
1152
+ Return a generator in format: (response, history)
1153
+ Eg.
1154
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1155
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1156
+ """
1157
+ if BaseStreamer is None:
1158
+ raise ModuleNotFoundError(
1159
+ 'The version of `transformers` is too low. Please make sure '
1160
+ 'that you have installed `transformers>=4.28.0`.'
1161
+ )
1162
+
1163
+ response_queue = queue.Queue(maxsize=20)
1164
+
1165
+ class ChatStreamer(BaseStreamer):
1166
+ def __init__(self, tokenizer) -> None:
1167
+ super().__init__()
1168
+ self.tokenizer = tokenizer
1169
+ self.queue = response_queue
1170
+ self.query = query
1171
+ self.history = history
1172
+ self.response = ''
1173
+ self.cache = []
1174
+ self.received_inputs = False
1175
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1176
+
1177
+ def put(self, value):
1178
+ if len(value.shape) > 1 and value.shape[0] > 1:
1179
+ raise ValueError('ChatStreamer only supports batch size 1')
1180
+ elif len(value.shape) > 1:
1181
+ value = value[0]
1182
+
1183
+ if not self.received_inputs:
1184
+ # The first received value is input_ids, ignore here
1185
+ self.received_inputs = True
1186
+ return
1187
+
1188
+ self.cache.extend(value.tolist())
1189
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1190
+ if token.strip() != '<|im_end|>':
1191
+ self.response = self.response + token
1192
+ history = self.history + [(self.query, self.response)]
1193
+ self.queue.put((self.response, history))
1194
+ self.cache = []
1195
+ else:
1196
+ self.end()
1197
+
1198
+ def end(self):
1199
+ self.queue.put(None)
1200
+
1201
+ def stream_producer():
1202
+ return self.chat(
1203
+ tokenizer=tokenizer,
1204
+ query=query,
1205
+ streamer=ChatStreamer(tokenizer=tokenizer),
1206
+ history=history,
1207
+ max_new_tokens=max_new_tokens,
1208
+ do_sample=do_sample,
1209
+ temperature=temperature,
1210
+ top_p=top_p,
1211
+ **kwargs,
1212
+ )
1213
+
1214
+ def consumer():
1215
+ producer = threading.Thread(target=stream_producer)
1216
+ producer.start()
1217
+ while True:
1218
+ res = response_queue.get()
1219
+ if res is None:
1220
+ return
1221
+ yield res
1222
+
1223
+ return consumer()
1224
+
modeling_mmMamba_chat.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from dataclasses import dataclass
3
+ from typing import Any, List, Optional, Tuple, Union
4
+ from copy import deepcopy
5
+
6
+ import torch.distributed as dist
7
+ import torch.utils.checkpoint
8
+ import torch.nn as nn
9
+ import transformers
10
+
11
+ from peft import LoraConfig, get_peft_model
12
+ from torch import nn
13
+ from torch.nn import CrossEntropyLoss
14
+ from transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,
15
+ LlamaTokenizer, Qwen2ForCausalLM)
16
+ from transformers.modeling_outputs import CausalLMOutputWithPast
17
+ from transformers.modeling_utils import PreTrainedModel
18
+ from transformers.utils import logging as hf_logging
19
+ from transformers.trainer_pt_utils import LabelSmoother
20
+ from transformers.generation import GreedySearchDecoderOnlyOutput, SampleDecoderOnlyOutput, TextStreamer
21
+ IGNORE_TOKEN_ID = LabelSmoother.ignore_index
22
+
23
+ from .configuration_mmMamba_chat import mmMambaChatConfig
24
+ from .conversation import get_conv_template
25
+ from .modeling_mmMamba import mmMambaForCausalLM
26
+ from .modeling_mmMamba_embedding import mmMambaEmbedding
27
+ from transformers.cache_utils import Cache, DynamicCache
28
+ from typing import Any, Dict, List, Optional, Tuple, Union
29
+
30
+ import sys
31
+
32
+ from mamba_ssm.utils.generation import InferenceParams
33
+ from mamba_ssm.utils.generation import sample, update_graph_cache, modify_logit_for_repetition_penalty
34
+
35
+ import time
36
+ import logging
37
+
38
+ logger = hf_logging.get_logger(__name__)
39
+
40
+
41
+ def version_cmp(v1, v2, op='eq'):
42
+ import operator
43
+
44
+ from packaging import version
45
+ op_func = getattr(operator, op)
46
+ return op_func(version.parse(v1), version.parse(v2))
47
+
48
+ @torch.inference_mode()
49
+ def decode(
50
+ input_ids,
51
+ model,
52
+ max_length,
53
+ max_new_tokens=None,
54
+ top_k=1,
55
+ top_p=0.0,
56
+ min_p=0.0,
57
+ temperature=1.0,
58
+ repetition_penalty=1.0,
59
+ eos_token_id=None,
60
+ pad_token_id=None,
61
+ do_sample=False,
62
+ teacher_outputs=None,
63
+ vocab_size=None,
64
+ use_cache=False,
65
+ enable_timing=False,
66
+ streamer: Optional[TextStreamer] = None,
67
+ pixel_values=None,
68
+ hd_input_ids=None,
69
+ ):
70
+ """Decoding, either greedy or with top-k or top-p sampling.
71
+ If top-k = 0, don't limit the number of candidates (pure sampling).
72
+ Top-k and top-p can be used together. If top_k > 0 and top_p > 0, then top-k is applied first,
73
+ then top-p.
74
+ We assume that all sequences in the same batch have the same length.
75
+
76
+ Arguments:
77
+ input_ids: (batch, seq_len)
78
+ max_length: int
79
+ teacher_outputs (optional): (batch, seq_len). If provided, instead of sampling from the
80
+ logits, the next token is taken from the teacher_outputs. Useful for testing.
81
+ Returns: GreedySearchDecoderOnlyOutput or SampleDecoderOnlyOutput, with the following fields:
82
+ sequences: (batch, max_length)
83
+ scores: tuples of (batch, vocab_size)
84
+ """
85
+ if streamer is not None:
86
+ streamer.put(input_ids.cpu())
87
+
88
+ scores, sequences = [], [input_ids.cpu()]
89
+ if max_new_tokens is not None:
90
+ max_length = sequences[-1].shape[1] + max_new_tokens # override max_length if max_new_tokens is set
91
+
92
+ batch_size, seqlen_og = input_ids.shape
93
+ teacher_output_len = teacher_outputs.shape[1] if teacher_outputs is not None else 0
94
+
95
+ if not hasattr(model, "_decoding_cache"):
96
+ model._decoding_cache = None
97
+
98
+ model._decoding_cache = update_graph_cache(
99
+ model,
100
+ model._decoding_cache,
101
+ batch_size,
102
+ seqlen_og,
103
+ max_length,
104
+ )
105
+ inference_params = model._decoding_cache.inference_params
106
+ inference_params.reset(max_length, batch_size)
107
+
108
+ def get_logits(input_ids, inference_params):
109
+ decoding = inference_params.seqlen_offset > 0
110
+ if decoding:
111
+ position_ids = torch.full(
112
+ (batch_size, 1),
113
+ inference_params.seqlen_offset,
114
+ dtype=torch.long,
115
+ device=input_ids.device,
116
+ )
117
+ else:
118
+ position_ids = None
119
+ if not decoding:
120
+ logits = model(
121
+ input_ids,
122
+ position_ids=position_ids,
123
+ inference_params=inference_params,
124
+ num_last_tokens=1,
125
+ return_dict=True,
126
+ pixel_values=pixel_values,
127
+ ).logits.squeeze(dim=1)
128
+ else:
129
+ logits = model._decoding_cache.run(
130
+ input_ids, position_ids, inference_params.seqlen_offset
131
+ ).squeeze(dim=1)
132
+ return logits[..., :vocab_size] if vocab_size is not None else logits
133
+
134
+ def sample_tokens(logits, inference_params):
135
+ if teacher_outputs is None or teacher_output_len <= inference_params.seqlen_offset:
136
+ token = sample(logits, top_k=top_k, top_p=top_p, min_p=min_p, temperature=temperature)
137
+ else:
138
+ token = teacher_outputs[:, inference_params.seqlen_offset]
139
+ # return rearrange(token, "b -> b 1")
140
+ return token.unsqueeze(1)
141
+
142
+ def should_stop(current_token, inference_params):
143
+ if inference_params.seqlen_offset == 0:
144
+ return False
145
+ if eos_token_id is not None and (current_token == eos_token_id).all():
146
+ return True
147
+ if inference_params.seqlen_offset >= max_length - 1:
148
+ return True
149
+ return False
150
+
151
+ start = torch.cuda.Event(enable_timing=enable_timing)
152
+ end = torch.cuda.Event(enable_timing=enable_timing)
153
+
154
+ if enable_timing:
155
+ start.record()
156
+ sequences_cat = input_ids
157
+
158
+ while not should_stop(sequences[-1], inference_params):
159
+ torch.cuda.synchronize()
160
+ torch.cuda.reset_max_memory_allocated()
161
+ score = get_logits(sequences[-1].cuda(), inference_params)
162
+ inference_params.seqlen_offset += sequences[-1].shape[1]
163
+
164
+ if repetition_penalty == 1.0:
165
+ sampled_tokens = sample_tokens(score, inference_params)
166
+ else:
167
+ logits = modify_logit_for_repetition_penalty(
168
+ score.clone(), sequences_cat, repetition_penalty
169
+ )
170
+ sampled_tokens = sample_tokens(logits, inference_params)
171
+ sequences_cat = torch.cat([sequences_cat, sampled_tokens], dim=1)
172
+
173
+ sequences.append(sampled_tokens.cpu())
174
+ if streamer is not None:
175
+ streamer.put(sampled_tokens.cpu())
176
+
177
+
178
+ if streamer is not None:
179
+ streamer.end()
180
+ if enable_timing:
181
+ end.record()
182
+ torch.cuda.synchronize()
183
+ print(f"Prompt processing + decoding time: {(start.elapsed_time(end)):.0f}ms")
184
+ output_cls = GreedySearchDecoderOnlyOutput if top_k == 1 else SampleDecoderOnlyOutput
185
+ return output_cls(sequences=torch.cat(sequences, dim=1), scores=tuple(scores))
186
+
187
+
188
+ class MambaGenerationMixin:
189
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
190
+ raise NotImplementedError
191
+
192
+ def generate(
193
+ self,
194
+ input_ids,
195
+ do_sample=False,
196
+ max_length=256,
197
+ max_new_tokens=None,
198
+ top_k=1,
199
+ top_p=0.0,
200
+ temperature=1.0,
201
+ return_dict_in_generate=False,
202
+ output_scores=False,
203
+ **kwargs
204
+ ):
205
+ if not do_sample:
206
+ top_k = 1
207
+ output = decode(
208
+ input_ids, self, max_length=max_length, max_new_tokens=max_new_tokens, top_k=top_k, top_p=top_p, temperature=temperature, **kwargs
209
+ )
210
+ if not output_scores:
211
+ output.scores = None
212
+ return output if return_dict_in_generate else output.sequences
213
+
214
+
215
+ class mmMambaChatModel(PreTrainedModel):
216
+ config_class = mmMambaChatConfig
217
+ # main_input_name = 'pixel_values'
218
+ _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer',
219
+ 'Phi3DecoderLayer', 'Qwen2DecoderLayer']
220
+ _supports_flash_attn_2 = True
221
+
222
+ def __init__(self, config: mmMambaChatConfig, embedding_model=None, language_model=None):
223
+ super().__init__(config)
224
+
225
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
226
+ image_size = config.force_image_size or config.embedding_config.image_size
227
+ patch_size = config.embedding_config.patch_size
228
+ self.image_size = image_size
229
+ self.patch_size = patch_size
230
+ self.select_layer = config.select_layer
231
+ self.template = config.template
232
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
233
+ self.downsample_ratio = config.downsample_ratio
234
+ self.ps_version = config.ps_version
235
+ self.use_thumbnail = config.use_thumbnail
236
+
237
+ if embedding_model is not None:
238
+ self.embedding_model = embedding_model
239
+ else:
240
+ self.embedding_model = mmMambaEmbedding(config.embedding_config)
241
+
242
+ if language_model is not None:
243
+ self.language_model = language_model
244
+ else:
245
+ self.language_model = mmMambaForCausalLM(config.llm_config)
246
+
247
+ self.img_context_token_id = None
248
+ self.conv_template = get_conv_template(self.template)
249
+ self.system_message = self.conv_template.system_message
250
+ self.num_samples = 0
251
+
252
+
253
+ def forward(
254
+ self,
255
+ input_ids: torch.LongTensor = None,
256
+ pixel_values: torch.FloatTensor = None,
257
+ input_embeds: Optional[torch.FloatTensor] = None,
258
+ position_ids: Optional[torch.LongTensor] = None,
259
+ image_flags: Optional[torch.LongTensor] = None,
260
+ labels: Optional[torch.LongTensor] = None,
261
+ use_cache: Optional[bool] = True,
262
+ output_attentions: Optional[bool] = None,
263
+ output_hidden_states: Optional[bool] = None,
264
+ return_dict: Optional[bool] = None,
265
+ statistics: Optional[torch.LongTensor] = None,
266
+ loss_weight: Optional[List] = None,
267
+ loss_reduction_all_gather: Optional[bool] = False,
268
+ query = None,
269
+ hd_input_ids = None,
270
+ hd_input_embeds = None,
271
+ hd_labels = None,
272
+ hd_loss_weight = None,
273
+ inference_params = None,
274
+ num_last_tokens: int = 0,
275
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
276
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
277
+ if pixel_values is not None or input_ids.shape[0] > 1:
278
+ if image_flags is not None:
279
+ #image_flags = image_flags.squeeze(-1)
280
+ pixel_values = pixel_values[image_flags == 1]
281
+ if pixel_values==[]:
282
+ pixel_values = None
283
+ if getattr(self.embedding_model.config, 'pixel_shuffle_loc', None) in ['post']:
284
+ assert hd_input_ids is not None, 'hd_input_ids is required for pixel_shuffle_loc=post'
285
+ embedding_input_ids = hd_input_ids
286
+ else:
287
+ embedding_input_ids = input_ids
288
+ image_embeds, input_embeds = self.embedding_model(input_ids=embedding_input_ids,
289
+ pixel_values=pixel_values,
290
+ use_cache=use_cache,
291
+ return_dict=return_dict,
292
+ inference_params=inference_params)
293
+
294
+ B, N = embedding_input_ids.shape
295
+ image_batch_size = pixel_values.shape[0] if pixel_values is not None else 0
296
+ C = image_embeds.shape[-1]
297
+ input_embeds = input_embeds.reshape(B * N, C)
298
+
299
+ if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
300
+ #print(f'dynamic ViT batch size: {image_batch_size}, images per sample: {image_batch_size / B}, dynamic token length: {N}')
301
+ if statistics is not None:
302
+ num_samples, num_padding_tokens, num_padding_images = statistics.tolist()
303
+ self.num_samples += num_samples
304
+ print(f'total_samples={self.num_samples}, {num_samples=}, {num_padding_tokens=}, {num_padding_images=}')
305
+
306
+ if image_batch_size != 0:
307
+ if getattr(self.embedding_model.config, 'pixel_shuffle_loc', None) == 'post':
308
+ B, N = input_ids.shape
309
+ llm_input_embeds = torch.zeros(input_ids.shape[1], C, device=input_ids.device, dtype=input_embeds.dtype)
310
+ llm_selected = input_ids.flatten() == self.img_context_token_id
311
+ hd_llm_selected = hd_input_ids.flatten() == self.img_context_token_id
312
+ llm_input_embeds[~llm_selected] = input_embeds[~hd_llm_selected]
313
+ llm_input_embeds[llm_selected] = image_embeds.reshape(-1, C)
314
+ input_embeds = llm_input_embeds
315
+
316
+ input_embeds = input_embeds.reshape(B, N, C)
317
+
318
+ else:
319
+ input_embeds = self.embedding_model.get_input_embeddings(input_ids)
320
+ hd_input_ids = input_ids
321
+ hd_input_embeds = input_embeds
322
+ next_past_key_values = []
323
+ if getattr(self.embedding_model.config, 'pixel_shuffle_loc', None) in ['post']:
324
+ embedding_input_embeds = hd_input_embeds
325
+ else:
326
+ embedding_input_embeds = input_embeds
327
+ for layer_idx, layer_module in enumerate(self.embedding_model.encoder):
328
+ outputs = layer_module(
329
+ hidden_states=embedding_input_embeds,
330
+ use_cache=use_cache,
331
+ return_dict=return_dict,
332
+ inference_params=inference_params,
333
+ )
334
+ embedding_input_embeds = outputs[0]
335
+
336
+ input_embeds = embedding_input_embeds
337
+
338
+ if self.config.normalize_encoder_output:
339
+ input_embeds = input_embeds / input_embeds.norm(dim=-1, keepdim=True)
340
+
341
+ outputs = self.language_model(
342
+ inputs_embeds=input_embeds,
343
+ use_cache=use_cache,
344
+ output_attentions=output_attentions,
345
+ output_hidden_states=output_hidden_states,
346
+ return_dict=return_dict,
347
+ inference_params=inference_params,
348
+ num_last_tokens=num_last_tokens
349
+ )
350
+ logits = outputs.logits
351
+
352
+ loss = None
353
+ if labels is not None and loss_weight is not None:
354
+ loss_weight = torch.tensor(loss_weight, dtype=torch.float32, device=labels.device)
355
+ # Shift so that tokens < n predict n
356
+ shift_logits = logits[..., :-1, :].contiguous()
357
+ shift_labels = labels[..., 1:].contiguous()
358
+ shift_weights = loss_weight[..., 1:].contiguous()
359
+ # Flatten the tokens
360
+ loss_fct = CrossEntropyLoss(reduction='none')
361
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
362
+ shift_labels = shift_labels.view(-1)
363
+ shift_weights = shift_weights.view(-1)
364
+ # Enable model parallelism
365
+ shift_labels = shift_labels.to(shift_logits.device)
366
+ shift_weights = shift_weights.to(shift_logits.device)
367
+ loss = loss_fct(shift_logits, shift_labels)
368
+
369
+ shift_weights_sum = shift_weights.sum()
370
+ if loss_reduction_all_gather:
371
+ dist.all_reduce(shift_weights_sum, op=dist.ReduceOp.AVG)
372
+
373
+ loss = loss * shift_weights
374
+ loss = loss.sum() / shift_weights_sum
375
+ elif labels is not None:
376
+ # Shift so that tokens < n predict n
377
+ shift_logits = logits[..., :-1, :].contiguous()
378
+ shift_labels = labels[..., 1:].contiguous()
379
+ # Flatten the tokens
380
+ loss_fct = CrossEntropyLoss()
381
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
382
+ shift_labels = shift_labels.view(-1)
383
+ # Enable model parallelism
384
+ shift_labels = shift_labels.to(shift_logits.device)
385
+ loss = loss_fct(shift_logits, shift_labels)
386
+
387
+ if not return_dict:
388
+ output = (logits,) + outputs[1:]
389
+ return (loss,) + output if loss is not None else output
390
+
391
+ next_past_key_values = None
392
+
393
+ return CausalLMOutputWithPast(
394
+ loss=loss,
395
+ logits=logits,
396
+ past_key_values=next_past_key_values,
397
+ hidden_states=outputs.hidden_states,
398
+ attentions=outputs.attentions,
399
+ )
400
+
401
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
402
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
403
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
404
+ if history is not None or return_history:
405
+ print('Now multi-turn chat is not supported in batch_chat.')
406
+ raise NotImplementedError
407
+
408
+ if image_counts is not None:
409
+ num_patches_list = image_counts
410
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
411
+
412
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
413
+ self.img_context_token_id = img_context_token_id
414
+
415
+ if verbose and pixel_values is not None:
416
+ image_bs = pixel_values.shape[0]
417
+ print(f'dynamic ViT batch size: {image_bs}')
418
+
419
+ queries = []
420
+ for idx, num_patches in enumerate(num_patches_list):
421
+ question = questions[idx]
422
+ if pixel_values is not None and '<image>' not in question:
423
+ question = '<image>\n' + question
424
+ template = get_conv_template(self.template)
425
+ template.append_message(template.roles[0], question)
426
+ template.append_message(template.roles[1], None)
427
+ query = template.get_prompt()
428
+
429
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
430
+ query = query.replace('<image>', image_tokens, 1)
431
+ queries.append(query)
432
+
433
+ tokenizer.padding_side = 'left'
434
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
435
+ input_ids = model_inputs['input_ids'].cuda()
436
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
437
+ generation_config['eos_token_id'] = eos_token_id
438
+ generation_output = self.generate(
439
+ pixel_values=pixel_values,
440
+ input_ids=input_ids,
441
+ **generation_config
442
+ )
443
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
444
+ responses = [response.split(template.sep)[0].strip() for response in responses]
445
+ return responses
446
+
447
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
448
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
449
+ verbose=False):
450
+
451
+ if history is None and pixel_values is not None and '<image>' not in question:
452
+ question = '<image>\n' + question
453
+
454
+ if num_patches_list is None:
455
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
456
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
457
+
458
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
459
+ self.img_context_token_id = img_context_token_id
460
+
461
+ template = get_conv_template(self.template)
462
+ template.system_message = self.system_message
463
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
464
+
465
+ history = [] if history is None else history
466
+ for (old_question, old_answer) in history:
467
+ template.append_message(template.roles[0], old_question)
468
+ template.append_message(template.roles[1], old_answer)
469
+ template.append_message(template.roles[0], question)
470
+ template.append_message(template.roles[1], None)
471
+ query = template.get_prompt()
472
+
473
+ if verbose and pixel_values is not None:
474
+ image_bs = pixel_values.shape[0]
475
+ print(f'dynamic ViT batch size: {image_bs}')
476
+
477
+ hd_query = deepcopy(query)
478
+ for num_patches in num_patches_list:
479
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
480
+ hd_image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * int(self.num_image_token // self.downsample_ratio**2) * num_patches + IMG_END_TOKEN
481
+ query = query.replace('<image>', image_tokens, 1)
482
+ hd_query = hd_query.replace('<image>', hd_image_tokens, 1)
483
+ #print(hd_query)
484
+
485
+ model_inputs = tokenizer(query, return_tensors='pt')
486
+ hd_model_inputs = tokenizer(hd_query, return_tensors='pt')
487
+ input_ids = model_inputs['input_ids'].cuda()
488
+ hd_input_ids = hd_model_inputs['input_ids'].cuda()
489
+
490
+ generation_config['eos_token_id'] = eos_token_id
491
+ generation_output = self.generate(
492
+ pixel_values=pixel_values,
493
+ input_ids=input_ids,
494
+ hd_input_ids=hd_input_ids,
495
+ **generation_config
496
+ )
497
+ generation_output = generation_output[:, input_ids.shape[1]:]
498
+
499
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
500
+ response = response.split(template.sep)[0].strip()
501
+ history.append((question, response))
502
+ if return_history:
503
+ return response, history
504
+ else:
505
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
506
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
507
+ if verbose:
508
+ print(query_to_print, response)
509
+ return response
510
+
511
+ def generate(self, *args, **kwargs):
512
+ return MambaGenerationMixin.generate(self, *args, **kwargs)
513
+
514
+ def allocate_inference_cache(self, *args, **kwargs):
515
+ dict1= self.embedding_model.allocate_inference_cache(*args, **kwargs)
516
+ dict2= self.language_model.allocate_inference_cache(*args, **kwargs)
517
+ return {**dict1, **dict2}
modeling_mmMamba_embedding.py ADDED
@@ -0,0 +1,1063 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The mmMamba 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
+ import math
17
+ import queue
18
+ import threading
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+ from functools import partial
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 (
31
+ BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ )
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.cache_utils import Cache
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from fla.modules import FusedRMSNormSwishGate, RMSNorm, ShortConvolution
44
+ import copy
45
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
46
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
47
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
48
+ from transformers.cache_utils import Cache
49
+ import time
50
+ from timm.models.layers import DropPath
51
+
52
+ compute_ARank = False # [ARank] Set this to True to compute attention rank
53
+
54
+ try:
55
+ from transformers.generation.streamers import BaseStreamer
56
+ except: # noqa # pylint: disable=bare-except
57
+ BaseStreamer = None
58
+
59
+ from .configuration_mmMamba_embedding import mmMambaEmbeddingConfig
60
+
61
+ import time
62
+
63
+ from .configuration_mmMamba import mmMambaConfig
64
+
65
+ try:
66
+ from flash_attn import flash_attn_with_kvcache
67
+ except ImportError:
68
+ flash_attn_with_kvcache = None
69
+
70
+ try:
71
+ from flash_attn.layers.rotary import RotaryEmbedding
72
+ except ImportError:
73
+ RotaryEmbedding = None
74
+
75
+ import torch.nn.functional as F
76
+
77
+ logger = logging.get_logger(__name__)
78
+
79
+ _CONFIG_FOR_DOC = "mmMambaEmbeddingConfig"
80
+
81
+ flash_attn_func, flash_attn_varlen_func = None, None
82
+ pad_input, index_first_axis, unpad_input = None, None, None
83
+ def _import_flash_attn():
84
+ global flash_attn_func, flash_attn_varlen_func
85
+ global pad_input, index_first_axis, unpad_input
86
+ try:
87
+ from flash_attn import flash_attn_func as _flash_attn_func, flash_attn_varlen_func as _flash_attn_varlen_func
88
+ from flash_attn.bert_padding import pad_input as _pad_input, index_first_axis as _index_first_axis, unpad_input as _unpad_input
89
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
90
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
91
+ except ImportError:
92
+ raise ImportError("flash_attn is not installed.")
93
+
94
+ _import_flash_attn()
95
+
96
+ def _update_kv_cache(kv, inference_params, layer_idx):
97
+ """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)"""
98
+ # Pre-allocate memory for key-values for inference.
99
+ num_heads, head_dim = kv.shape[-2:]
100
+ assert layer_idx in inference_params.key_value_memory_dict
101
+ kv_cache, _ = inference_params.key_value_memory_dict[layer_idx]
102
+ # Adjust key and value for inference
103
+ batch_start = inference_params.batch_size_offset
104
+ batch_end = batch_start + kv.shape[0]
105
+ sequence_start = inference_params.seqlen_offset
106
+ sequence_end = sequence_start + kv.shape[1]
107
+ assert batch_end <= kv_cache.shape[0]
108
+ assert sequence_end <= kv_cache.shape[1]
109
+ assert kv_cache is not None
110
+ kv_cache[batch_start:batch_end, sequence_start:sequence_end, ...] = kv
111
+ return kv_cache[batch_start:batch_end, :sequence_end, ...]
112
+
113
+
114
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->mmMamba
115
+ class mmMambaRMSNorm(nn.Module):
116
+ def __init__(self, hidden_size, eps=1e-6):
117
+ """
118
+ mmMambaRMSNorm is equivalent to T5LayerNorm
119
+ """
120
+ super().__init__()
121
+ self.weight = nn.Parameter(torch.ones(hidden_size))
122
+ self.variance_epsilon = eps
123
+
124
+ def forward(self, hidden_states):
125
+ input_dtype = hidden_states.dtype
126
+ hidden_states = hidden_states.to(torch.float32)
127
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
128
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
129
+ return self.weight * hidden_states.to(input_dtype)
130
+
131
+
132
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->mmMamba
133
+ class mmMambaRotaryEmbedding(nn.Module):
134
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
135
+ super().__init__()
136
+
137
+ self.dim = dim
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.base = base
140
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
141
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
142
+
143
+ # Build here to make `torch.jit.trace` work.
144
+ self._set_cos_sin_cache(
145
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
146
+ )
147
+
148
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
149
+ self.max_seq_len_cached = seq_len
150
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
151
+
152
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
153
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
154
+ emb = torch.cat((freqs, freqs), dim=-1)
155
+ self.cos_cached = emb.cos().to(dtype)
156
+ self.sin_cached = emb.sin().to(dtype)
157
+ #self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
158
+ #self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
159
+
160
+ def forward(self, x, seq_len=None):
161
+ # x: [bs, num_attention_heads, seq_len, head_size]
162
+ if seq_len > self.max_seq_len_cached:
163
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
164
+
165
+ return (
166
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
167
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
168
+ )
169
+
170
+
171
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->mmMamba
172
+ class mmMambaLinearScalingRotaryEmbedding(mmMambaRotaryEmbedding):
173
+ """mmMambaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
174
+
175
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
176
+ self.scaling_factor = scaling_factor
177
+ super().__init__(dim, max_position_embeddings, base, device)
178
+
179
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
180
+ self.max_seq_len_cached = seq_len
181
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
182
+ t = t / self.scaling_factor
183
+
184
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
185
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
186
+ emb = torch.cat((freqs, freqs), dim=-1)
187
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
188
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
189
+
190
+
191
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->mmMamba
192
+ class mmMambaDynamicNTKScalingRotaryEmbedding(mmMambaRotaryEmbedding):
193
+ """mmMambaRotaryEmbedding extended with Dynamic NTK scaling.
194
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
195
+ """
196
+
197
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
198
+ self.scaling_factor = scaling_factor
199
+ super().__init__(dim, max_position_embeddings, base, device)
200
+
201
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
202
+ self.max_seq_len_cached = seq_len
203
+
204
+ if seq_len > self.max_position_embeddings:
205
+ base = self.base * (
206
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
207
+ ) ** (self.dim / (self.dim - 2))
208
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
209
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
210
+
211
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
212
+
213
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
214
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
215
+ emb = torch.cat((freqs, freqs), dim=-1)
216
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
217
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
218
+
219
+
220
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
221
+ def rotate_half(x):
222
+ """Rotates half the hidden dims of the input."""
223
+ x1 = x[..., : x.shape[-1] // 2]
224
+ x2 = x[..., x.shape[-1] // 2 :]
225
+ return torch.cat((-x2, x1), dim=-1)
226
+
227
+
228
+ class mmMambaMLP(nn.Module):
229
+ def __init__(self, config):
230
+ super().__init__()
231
+ self.config = config
232
+ self.hidden_size = config.hidden_size
233
+ self.intermediate_size = config.intermediate_size
234
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
235
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
236
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
237
+ self.act_fn = ACT2FN[config.hidden_act]
238
+
239
+ def forward(self, x):
240
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
241
+
242
+ return down_proj
243
+
244
+
245
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
246
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
247
+ """
248
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
249
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
250
+ """
251
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
252
+ if n_rep == 1:
253
+ return hidden_states
254
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
255
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
256
+
257
+ def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
258
+ """
259
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
260
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
261
+ """
262
+ batch, num_key_value_heads, head_dim = hidden_states.shape
263
+ if n_rep == 1:
264
+ return hidden_states
265
+ hidden_states = hidden_states[:, :, None, :].expand(batch, num_key_value_heads, n_rep, head_dim)
266
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, head_dim)
267
+
268
+ class MHA_LM(nn.Module):
269
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
270
+
271
+ def __init__(self, config: mmMambaEmbeddingConfig, layer_idx: int):
272
+ super().__init__()
273
+ self.config = config
274
+ self.layer_idx = layer_idx
275
+ self.hidden_size = config.hidden_size
276
+ self.num_heads = config.num_attention_heads
277
+ self.head_dim = self.hidden_size // self.num_heads
278
+ self.num_key_value_heads = config.num_key_value_heads
279
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
280
+ self.max_position_embeddings = config.max_position_embeddings
281
+ self.is_causal = True
282
+ self.rotary_emb_dim = self.head_dim
283
+ self.softmax_scale = None
284
+ self.causal = True
285
+
286
+ if (self.head_dim * self.num_heads) != self.hidden_size:
287
+ raise ValueError(
288
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
289
+ f" and `num_heads`: {self.num_heads})."
290
+ )
291
+
292
+ self.wqkv = nn.Linear(
293
+ self.hidden_size,
294
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
295
+ bias=False,
296
+ )
297
+
298
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
299
+ assert RotaryEmbedding is not None, "rotary requires flash_attn to be installed"
300
+ self.rotary_emb = RotaryEmbedding(
301
+ self.head_dim,
302
+ base=self.config.rope_theta,
303
+ interleaved=False,
304
+ device=self.wo.weight.device,
305
+ )
306
+
307
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
308
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
309
+
310
+ def _update_kv_cache(self, kv, inference_params):
311
+ """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)"""
312
+ assert self.layer_idx is not None, "Generation requires layer_idx in the constructor"
313
+ return _update_kv_cache(kv, inference_params, self.layer_idx)
314
+
315
+ def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params):
316
+ """
317
+ Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention.
318
+ q: (batch_size, seqlen_q, nheads, head_dim)
319
+ kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim)
320
+ """
321
+ assert inference_params is not None and inference_params.seqlen_offset > 0
322
+ if self.rotary_emb_dim > 0:
323
+ self.rotary_emb._update_cos_sin_cache(
324
+ inference_params.max_seqlen, device=q.device, dtype=q.dtype
325
+ )
326
+ rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached
327
+ else:
328
+ rotary_cos, rotary_sin = None, None
329
+ batch = q.shape[0]
330
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
331
+ kv_cache = kv_cache[:batch]
332
+ cache_seqlens = (
333
+ inference_params.lengths_per_sample[:batch]
334
+ if inference_params.lengths_per_sample is not None
335
+ else inference_params.seqlen_offset
336
+ )
337
+ assert flash_attn_with_kvcache is not None, "flash_attn must be installed"
338
+ context = flash_attn_with_kvcache(
339
+ q,
340
+ kv_cache[:, :, 0],
341
+ kv_cache[:, :, 1],
342
+ kv[:, :, 0],
343
+ kv[:, :, 1],
344
+ rotary_cos=rotary_cos,
345
+ rotary_sin=rotary_sin,
346
+ cache_seqlens=cache_seqlens,
347
+ softmax_scale=self.softmax_scale,
348
+ causal=self.causal,
349
+ rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False,
350
+ )
351
+ return context
352
+
353
+ def _update_kvcache_attention(self, q, kv, inference_params):
354
+ """Write kv to inference_params, then do attention"""
355
+ if (
356
+ inference_params.seqlen_offset == 0
357
+ or flash_attn_with_kvcache is None
358
+ ):
359
+ # TODO: this only uses seqlen_offset and not lengths_per_sample.
360
+ kv = self._update_kv_cache(kv, inference_params)
361
+ k, v = kv.unbind(dim=-3)
362
+ #k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
363
+ #v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
364
+ attn_output = flash_attn_func(
365
+ q, k, v, 0.0, softmax_scale=None, causal=self.causal
366
+ )
367
+ return attn_output
368
+ else:
369
+ batch = q.shape[0]
370
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
371
+ kv_cache = kv_cache[:batch]
372
+ cache_seqlens = (
373
+ inference_params.lengths_per_sample[:batch]
374
+ if inference_params.lengths_per_sample is not None
375
+ else inference_params.seqlen_offset
376
+ )
377
+ return flash_attn_with_kvcache(
378
+ q,
379
+ kv_cache[:, :, 0],
380
+ kv_cache[:, :, 1],
381
+ kv[:, :, 0],
382
+ kv[:, :, 1],
383
+ cache_seqlens=cache_seqlens,
384
+ softmax_scale=self.softmax_scale,
385
+ causal=self.causal,
386
+ )
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ inference_params = None,
392
+ output_attentions: bool = False,
393
+ cache_position: Optional[torch.LongTensor] = None,#------------------------------------------------------------------------
394
+ use_cache: bool = False,
395
+ **kwargs,
396
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
397
+ if inference_params is not None and self.layer_idx not in inference_params.key_value_memory_dict:
398
+ inference_params.key_value_memory_dict[self.layer_idx] = self.allocate_inference_cache(
399
+ hidden_states.shape[0], inference_params.max_seqlen, dtype=hidden_states.dtype
400
+ )
401
+ seqlen_offset = (
402
+ 0
403
+ if inference_params is None
404
+ else (
405
+ inference_params.lengths_per_sample
406
+ if inference_params.lengths_per_sample is not None
407
+ else inference_params.seqlen_offset
408
+ )
409
+ )
410
+
411
+ bsz, q_len, _ = hidden_states.size()
412
+ rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None
413
+
414
+ qkv = self.wqkv(hidden_states)
415
+ qkv = rearrange(
416
+ qkv,
417
+ "b q (h gs d) -> b q h gs d",
418
+ gs=2 + self.num_key_value_groups,
419
+ d=self.head_dim,
420
+ )
421
+
422
+ q = qkv[..., : self.num_key_value_groups, :]
423
+ q = rearrange(q, "b q h gs d -> b q (h gs) d")
424
+ kv = qkv[..., self.num_key_value_groups:, :].transpose(2,3)
425
+ #kv = rearrange(kv, "b q h gs d -> b q (h gs) d")
426
+ #kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim)
427
+
428
+ if (
429
+ inference_params is None
430
+ or inference_params.seqlen_offset == 0
431
+ or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0)
432
+ ):
433
+ if self.rotary_emb_dim > 0:
434
+ q, kv = self.rotary_emb(
435
+ q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen
436
+ )
437
+ if inference_params is None:
438
+ k, v = kv.unbind(dim=-3)
439
+ k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
440
+ v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
441
+ context = F.scaled_dot_product_attention(
442
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, scale=None
443
+ ).transpose(1, 2)
444
+ else:
445
+ context = self._update_kvcache_attention(q, kv, inference_params)
446
+ else:
447
+ context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params)
448
+ context = rearrange(context, "... h d -> ... (h d)")
449
+ out = self.wo(context)
450
+ return out
451
+
452
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None):
453
+ dtype = self.wo.weight.dtype if dtype is None else dtype
454
+ device = self.wo.weight.device
455
+ kv_cache = torch.empty(
456
+ batch_size, max_seqlen, 2, self.num_key_value_heads, self.head_dim, dtype=dtype, device=device,
457
+ )
458
+ return kv_cache, None
459
+
460
+ class Mamba2_LM(nn.Module):
461
+ """
462
+ LoLCATs attention implementation initialized from a
463
+ `LlamaAttention` or `MistralAttention` object (base_attn)
464
+
465
+ Most of the arguments are directly tied to argparse args
466
+ - For now we don't support padding.
467
+ """
468
+ def __init__(self, config: mmMambaConfig, layer_idx: Optional[int] = None,
469
+ elementwise_affine: Optional[bool] = True,
470
+ norm_eps: float = 1e-5,
471
+ ):
472
+ super().__init__()
473
+ self.config = config
474
+ self.hidden_size = config.hidden_size
475
+ self.num_heads = config.num_attention_heads
476
+ self.head_dim = self.hidden_size // self.num_heads
477
+ self.num_key_value_heads = config.num_key_value_heads
478
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
479
+ self.max_position_embeddings = config.max_position_embeddings
480
+ self.layer_idx = layer_idx
481
+ self.bias = False
482
+ self.chunk_size = 128
483
+ conv_bias = True
484
+ self.conv_bias = conv_bias
485
+ self.d_conv = 2
486
+ self.activation="silu"
487
+ self.max_position_embeddings = config.max_position_embeddings
488
+ self.rope_theta = config.rope_theta
489
+
490
+ self.wvkqgdt = nn.Linear(
491
+ self.hidden_size,
492
+ (self.num_heads + 2 * self.num_key_value_heads + self.num_heads) * self.head_dim + self.num_heads,
493
+ bias=self.bias
494
+ )
495
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
496
+
497
+ self.device = self.wvkqgdt.weight.device
498
+ self.dtype = self.wvkqgdt.weight.dtype
499
+
500
+ conv_dim = self.num_heads * self.head_dim + 2 * self.num_key_value_heads * self.head_dim
501
+
502
+ self.conv1d = nn.Conv1d(
503
+ in_channels=conv_dim,
504
+ out_channels=conv_dim,
505
+ bias=self.conv_bias,
506
+ kernel_size=self.d_conv,
507
+ groups=conv_dim,
508
+ padding=self.d_conv - 1,
509
+ device=self.device,
510
+ dtype=self.dtype
511
+ )
512
+ with torch.no_grad():
513
+ self.conv1d.weight.zero_()
514
+ self.conv1d.weight[:, 0, 1] = 1
515
+ self.conv1d.bias.zero_()
516
+
517
+ # Activation after conv
518
+ if self.activation == "identity":
519
+ self.act = nn.Identity()
520
+ elif self.activation in ["silu", "swish"]:
521
+ self.act = nn.SiLU()
522
+ else:
523
+ raise ValueError(f"Unknown activation {self.activation}")
524
+
525
+ self.g_norm_swish_gate = FusedRMSNormSwishGate(hidden_size=self.head_dim, elementwise_affine=elementwise_affine, eps=norm_eps).to(self.dtype).to(self.device)
526
+
527
+ dt = torch.exp(
528
+ torch.rand(self.num_heads, dtype=self.dtype, device=self.device) * (math.log(0.1) - math.log(0.001))
529
+ + math.log(0.001)
530
+ )
531
+ dt = torch.clamp(dt, min=0.001)
532
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
533
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
534
+ self.dt_bias = nn.Parameter(inv_dt)
535
+ self.dt_bias._no_weight_decay = True
536
+
537
+ A_log_bias = torch.zeros(self.num_heads, dtype=self.dtype, device=self.device)
538
+ self.A_log_bias = nn.Parameter(A_log_bias)
539
+ self.A_log_bias._no_weight_decay = True
540
+
541
+ def forward(self,
542
+ hidden_states: torch.Tensor,
543
+ inference_params = None,
544
+ output_attentions: bool = False,
545
+ use_cache: bool = True,
546
+ **kwargs,
547
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
548
+ hidden_states = hidden_states.to(self.dtype)
549
+ vkqgdt = self.wvkqgdt(hidden_states)
550
+ vkq, g, dt = torch.split(
551
+ vkqgdt,
552
+ [
553
+ (2*self.num_key_value_heads+self.num_heads) * self.head_dim,
554
+ self.num_heads * self.head_dim,
555
+ self.num_heads,
556
+ ],
557
+ dim=2,
558
+ )
559
+ batch, seqlen, _ = hidden_states.shape
560
+ conv_state, ssm_state = None, None
561
+ if inference_params is not None:
562
+ conv_state, ssm_state = self._get_states_from_cache(inference_params, batch)
563
+
564
+ if use_cache and inference_params.seqlen_offset==0:
565
+ vkq, new_conv_states = causal_conv1d_fn(
566
+ vkq.transpose(1, 2),
567
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
568
+ self.conv1d.bias,
569
+ initial_states=None,
570
+ return_final_states=True,
571
+ activation=None if self.activation == "identity" else self.activation,
572
+ )
573
+
574
+ v, k, q = torch.split(
575
+ vkq,
576
+ [
577
+ self.num_key_value_heads * self.head_dim,
578
+ self.num_key_value_heads * self.head_dim,
579
+ self.num_heads * self.head_dim,
580
+ ],
581
+ dim=1,
582
+ )
583
+
584
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
585
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
586
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
587
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
588
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
589
+
590
+ A = -torch.exp(self.A_log_bias.float())
591
+
592
+ y, new_ssm_states = mamba_chunk_scan_combined(
593
+ x = v,
594
+ #x = v / F.softplus(A_log).to(v.dtype).unsqueeze(-1),
595
+ dt=dt,
596
+ dt_softplus=True,
597
+ A=A,
598
+ B=k,
599
+ C=q,
600
+ chunk_size=self.chunk_size,
601
+ dt_bias=self.dt_bias,
602
+ initial_states=None, # currently not supported by mamba_ssm.utils.generation
603
+ return_final_states=True,
604
+ )
605
+
606
+ conv_state.copy_(new_conv_states)
607
+ ssm_state.copy_(new_ssm_states)
608
+
609
+ elif use_cache and inference_params.seqlen_offset>0:
610
+
611
+ vkq = causal_conv1d_update(
612
+ vkq.transpose(1, 2).squeeze(-1),
613
+ conv_state,
614
+ self.conv1d.weight.squeeze(1),
615
+ self.conv1d.bias,
616
+ self.activation,
617
+ )
618
+
619
+ v, k, q = torch.split(
620
+ vkq,
621
+ [
622
+ self.num_key_value_heads * self.head_dim,
623
+ self.num_key_value_heads * self.head_dim,
624
+ self.num_heads * self.head_dim,
625
+ ],
626
+ dim=1,
627
+ )
628
+
629
+ v = rearrange(v, "b (h n) -> b h n", h=self.num_key_value_heads)
630
+ k = rearrange(k, "b (h n) -> b h n", h=self.num_key_value_heads)
631
+ q = rearrange(q, "b (h n) -> b h n", h=self.num_heads)
632
+ k = repeat_kv2(k, self.num_key_value_groups)
633
+ v = repeat_kv2(v, self.num_key_value_groups)
634
+
635
+ dt = dt.transpose(1, 2).squeeze(-1)
636
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
637
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
638
+ A = -torch.exp(self.A_log_bias.float())
639
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.head_dim).to(dtype=torch.float32)
640
+ D = torch.zeros((self.num_heads, self.head_dim), dtype=A.dtype, device=A.device)
641
+
642
+ y = selective_state_update(
643
+ ssm_state,
644
+ v,
645
+ dt,
646
+ A=A,
647
+ B=k,
648
+ C=q,
649
+ D=D,
650
+ dt_bias=dt_bias,
651
+ dt_softplus=True,
652
+ )
653
+
654
+ else:
655
+ vkq = causal_conv1d_fn(
656
+ vkq.transpose(1, 2),
657
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
658
+ self.conv1d.bias,
659
+ initial_states=None,
660
+ return_final_states=False,
661
+ activation=None if self.activation == "identity" else self.activation,
662
+ )
663
+
664
+ v, k, q = torch.split(
665
+ vkq,
666
+ [
667
+ self.num_key_value_heads * self.head_dim,
668
+ self.num_key_value_heads * self.head_dim,
669
+ self.num_heads * self.head_dim,
670
+ ],
671
+ dim=1,
672
+ )
673
+
674
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
675
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
676
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
677
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
678
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
679
+
680
+ A = -torch.exp(self.A_log_bias.float())
681
+
682
+ y = mamba_chunk_scan_combined(
683
+ x = v,
684
+ dt=dt,
685
+ dt_softplus=True,
686
+ A=A,
687
+ B=k,
688
+ C=q,
689
+ chunk_size=self.chunk_size,
690
+ dt_bias=self.dt_bias,
691
+ initial_states=None, # currently not supported by mamba_ssm.utils.generation
692
+ return_final_states=False,
693
+ )
694
+
695
+ g = rearrange(g, 'b l (h d) -> b l h d', h=self.num_heads)
696
+ y_true = self.g_norm_swish_gate(y, g)
697
+ y_true = y_true.view(batch, seqlen, self.hidden_size)
698
+ y_true = self.o_proj(y_true)
699
+
700
+ return y_true
701
+
702
+ def _get_states_from_cache(self, inference_params, batch_size, initialize_states=False):
703
+ device = self.conv1d.weight.device
704
+ dtype = self.conv1d.weight.dtype
705
+ assert self.layer_idx is not None
706
+ if self.layer_idx not in inference_params.key_value_memory_dict:
707
+ batch_shape = (batch_size,)
708
+ conv_state = torch.zeros(
709
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
710
+ )
711
+ ssm_state = torch.zeros(
712
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
713
+ )
714
+ inference_params.key_value_memory_dict[self.layer_idx] = (conv_state, ssm_state)
715
+ else:
716
+ conv_state, ssm_state = inference_params.key_value_memory_dict[self.layer_idx]
717
+ # TODO: What if batch size changes between generation, and we reuse the same states?
718
+ if initialize_states:
719
+ conv_state.zero_()
720
+ ssm_state.zero_()
721
+ return conv_state, ssm_state
722
+
723
+
724
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
725
+ device = self.conv1d.weight.device
726
+ dtype = self.conv1d.weight.dtype
727
+ conv_state = torch.zeros(
728
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
729
+ )
730
+
731
+ ssm_state = torch.zeros(
732
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
733
+ )
734
+ return conv_state, ssm_state
735
+
736
+
737
+ mmMamba_ATTENTION_CLASSES = {
738
+ 'mha': MHA_LM,
739
+ "mamba2":Mamba2_LM
740
+ }
741
+
742
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
743
+ class mmMambaDecoderLayer(nn.Module):
744
+ def __init__(self, config: mmMambaEmbeddingConfig, layer_idx: int, drop_path_rate=0.0):
745
+ super().__init__()
746
+ self.hidden_size = config.hidden_size
747
+ self.config = config
748
+ self.layer_idx = layer_idx
749
+
750
+ self.attention = mmMamba_ATTENTION_CLASSES[config.layers_block_type[layer_idx]](config=config, layer_idx=layer_idx)
751
+
752
+ self.feed_forward = mmMambaMLP(config)
753
+ self.attention_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
754
+ self.ffn_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
755
+
756
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
757
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
758
+
759
+ def forward(
760
+ self,
761
+ hidden_states: torch.Tensor,
762
+ inference_params = None,
763
+ output_attentions: Optional[bool] = False,
764
+ use_cache: Optional[bool] = True,
765
+ **kwargs,
766
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
767
+ """
768
+ Args:
769
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
770
+ output_attentions (`bool`, *optional*):
771
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
772
+ returned tensors for more detail.
773
+ use_cache (`bool`, *optional*)
774
+ """
775
+ residual = hidden_states
776
+
777
+ hidden_states = self.attention_norm(hidden_states)
778
+
779
+ # Self Attention
780
+ hidden_states = self.attention(
781
+ hidden_states=hidden_states,
782
+ inference_params=inference_params,
783
+ output_attentions=output_attentions,
784
+ use_cache=use_cache,
785
+ **kwargs,
786
+ )
787
+ hidden_states = residual + self.drop_path1(hidden_states)
788
+
789
+ # Fully Connected
790
+ residual = hidden_states
791
+ hidden_states = self.ffn_norm(hidden_states)
792
+ hidden_states = self.feed_forward(hidden_states)
793
+
794
+ hidden_states = residual + self.drop_path2(hidden_states)
795
+
796
+ outputs = (hidden_states,)
797
+
798
+ if output_attentions:
799
+ outputs += (self_attn_weights,)
800
+
801
+ return outputs
802
+
803
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
804
+ return self.attention.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
805
+
806
+
807
+ class VisionEmbeddings(nn.Module):
808
+ def __init__(self, config: mmMambaEmbeddingConfig):
809
+ super().__init__()
810
+ self.config = config
811
+ self.embed_dim = config.hidden_size
812
+ self.image_size = config.image_size
813
+ self.patch_size = config.patch_size
814
+
815
+ self.class_embedding = nn.Parameter(
816
+ torch.randn(1, 1, self.embed_dim),
817
+ )
818
+
819
+ self.patch_embedding = nn.Conv2d(
820
+ in_channels=self.config.num_channels, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
821
+ )
822
+
823
+ self.num_patches = (self.image_size // self.patch_size) ** 2
824
+ self.num_positions = self.num_patches + 1
825
+
826
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
827
+
828
+ self.post_init()
829
+
830
+ def post_init(self):
831
+ for m in self.modules():
832
+ if isinstance(m, nn.Conv2d):
833
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
834
+ if m.bias is not None:
835
+ nn.init.zeros_(m.bias)
836
+ if isinstance(m, nn.Linear):
837
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
838
+ if m.bias is not None:
839
+ nn.init.zeros_(m.bias)
840
+
841
+ def _get_pos_embed(self, pos_embed, H, W):
842
+ target_dtype = pos_embed.dtype
843
+ pos_embed = pos_embed.float().reshape(
844
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
845
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False).\
846
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
847
+ return pos_embed
848
+
849
+ def forward(self, pixel_values: torch.FloatTensor,
850
+ use_cls_token=False,
851
+ ) -> torch.Tensor:
852
+ target_dtype = self.patch_embedding.weight.dtype
853
+ pixel_values = pixel_values.to(target_dtype)
854
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
855
+ batch_size, _, height, width = patch_embeds.shape
856
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
857
+ if use_cls_token:
858
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
859
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
860
+ assert not self.config.use_2d_sincos_pos_embed, '2D SinCos pos embed is not supported with use_cls_token'
861
+ position_embedding = torch.cat([
862
+ self.position_embedding[:, :1, :],
863
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
864
+ ], dim=1)
865
+ embeddings = embeddings + position_embedding
866
+ else:
867
+ position_embedding = self._get_pos_embed(self.position_embedding[:, 1:, :], height, width).to(target_dtype)
868
+ embeddings = patch_embeds + position_embedding
869
+
870
+ return embeddings
871
+
872
+
873
+ class mmMambaEmbedding(PreTrainedModel):
874
+ config_class = mmMambaEmbeddingConfig
875
+ _supports_flash_attn_2 = True
876
+
877
+ def __init__(self, config: mmMambaEmbeddingConfig):
878
+ super().__init__(config)
879
+ self.config = config
880
+ self.hidden_size = self.config.hidden_size
881
+ self.gradient_checkpointing = True
882
+
883
+ self.vision_embeddings = VisionEmbeddings(config)
884
+ self.llm_text_embeddings = nn.Embedding(self.config.llm_vocab_size, self.config.llm_hidden_size)
885
+ self.special_token_maps = config.special_token_maps
886
+ if len(self.special_token_maps) > 0:
887
+ self.special_text_embeddings = nn.Embedding(len(config.special_token_maps), self.config.llm_hidden_size)
888
+
889
+ assert self.config.use_ls is False, 'LS is not supported in mmMamba'
890
+ if hasattr(config, 'drop_path_rate'):
891
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
892
+ else:
893
+ dpr = [0.0] * config.num_hidden_layers
894
+ self.encoder = nn.ModuleList([
895
+ mmMambaDecoderLayer(config, idx, dpr[idx]) for idx in range(config.num_hidden_layers)
896
+ ])
897
+
898
+ if self.config.use_pixel_shuffle_proj:
899
+ self.pixel_shuffle_proj = nn.Sequential(
900
+ nn.Linear(int(config.hidden_size / (config.downsample_ratio * config.downsample_ratio)), config.hidden_size),
901
+ nn.GELU(),
902
+ nn.Linear(config.hidden_size, config.hidden_size)
903
+ )
904
+
905
+ self.num_img_tokens = (self.config.image_size // self.config.patch_size) ** 2
906
+
907
+ def set_gradient_checkpointing(self):
908
+ self.gradient_checkpointing = True
909
+ for layer in self.encoder:
910
+ layer.gradient_checkpointing = True
911
+
912
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
913
+ pos_emb = self.vision_embeddings.position_embedding
914
+ _, num_positions, embed_dim = pos_emb.shape
915
+ cls_emb = pos_emb[:, :1, :]
916
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
917
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
918
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
919
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
920
+ self.vision_embeddings.position_embedding = nn.Parameter(pos_emb)
921
+ self.vision_embeddings.image_size = new_size
922
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
923
+
924
+ def replace_img_tokens(self, input_ids, hidden_states, vision_hidden_states):
925
+ img_context_token_mask = (input_ids == self.config.img_context_token_id)
926
+ hidden_states[img_context_token_mask] = hidden_states[img_context_token_mask] * 0.0 + vision_hidden_states.flatten(0, 1)
927
+
928
+ return hidden_states
929
+
930
+ def get_ignore_mask(self, input_ids):
931
+ ignore_ids = torch.tensor(
932
+ [self.special_token_maps[token] for token in [IMG_START_TOKEN, IMG_END_TOKEN]],
933
+ device=input_ids.device)
934
+ ignore_mask = torch.isin(input_ids, ignore_ids)
935
+
936
+ return ignore_mask
937
+
938
+ def get_text_mask(self, input_ids):
939
+ txt_mask = (input_ids != self.config.img_context_token_id)
940
+
941
+ return txt_mask
942
+
943
+ def get_input_embeddings(self, input_ids):
944
+ special_mask = input_ids > self.llm_text_embeddings.weight.shape[0] - 1
945
+ llm_embeddings = self.llm_text_embeddings(input_ids * (~special_mask).to(input_ids))
946
+
947
+ if len(self.special_token_maps) > 0:
948
+ special_embeddings = self.special_text_embeddings((input_ids - self.llm_text_embeddings.weight.shape[0]) * special_mask.to(input_ids))
949
+ special_mask = special_mask.unsqueeze(-1)
950
+ text_embeddings = llm_embeddings * (~special_mask).to(llm_embeddings) + \
951
+ special_embeddings * special_mask.to(llm_embeddings)
952
+ else:
953
+ text_embeddings = llm_embeddings
954
+
955
+ return text_embeddings
956
+
957
+ def get_txt_embeddings(self, input_ids):
958
+ B, L = input_ids.shape
959
+ txt_mask = (input_ids != self.config.img_context_token_id)
960
+ txt_embeddings = self.llm_text_embeddings(input_ids[txt_mask])
961
+ txt_embeddings = txt_embeddings.reshape(-1, txt_embeddings.shape[-1])
962
+
963
+ return txt_embeddings
964
+
965
+ def get_txt_feature(self, input_ids, feature):
966
+ B, L, C = feature.shape
967
+ txt_mask = (input_ids != self.config.img_context_token_id)
968
+ txt_feature = feature[txt_mask].reshape(-1, C)
969
+
970
+ return txt_feature
971
+
972
+ def get_img_feature(self, input_ids, feature):
973
+ B, L, C = feature.shape
974
+ img_mask = (input_ids == self.config.img_context_token_id)
975
+ img_feature = feature[img_mask].reshape(-1, C)
976
+
977
+ return img_feature
978
+
979
+ def pixel_shuffle(self, x, scale_factor=0.5):
980
+ if getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'post':
981
+ x = x.view(x.shape[0]//self.num_img_tokens, self.num_img_tokens, -1)
982
+
983
+ n, l, c = x.size()
984
+ h = w = int(l ** 0.5)
985
+ # N, W, H, C --> N, W, H * scale, C // scale
986
+ x = x.reshape(n, w, int(h * scale_factor), int(c / scale_factor))
987
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
988
+ x = x.permute(0, 2, 1, 3).contiguous()
989
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
990
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
991
+ int(c / (scale_factor * scale_factor)))
992
+ x = x.permute(0, 2, 1, 3).reshape(n, int(l * scale_factor * scale_factor), int(c / (scale_factor * scale_factor))).contiguous()
993
+
994
+ if getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'post':
995
+ x = x.view(int(x.shape[0]*self.num_img_tokens*(self.config.downsample_ratio**2)), -1)
996
+ return x
997
+
998
+ def forward(
999
+ self,
1000
+ input_ids: Optional[torch.LongTensor] = None,
1001
+ pixel_values: Optional[torch.FloatTensor] = None,
1002
+ inference_params = None,
1003
+ output_hidden_states: Optional[bool] = None,
1004
+ return_dict: Optional[bool] = None,
1005
+ use_cache: Optional[bool] = True,
1006
+ ):
1007
+ output_hidden_states = (
1008
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1009
+ )
1010
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1011
+ if pixel_values is not None:
1012
+ if len(pixel_values.shape) == 4:
1013
+ if self.gradient_checkpointing and self.training:
1014
+ vision_hidden_states = torch.utils.checkpoint.checkpoint(self.vision_embeddings, pixel_values)
1015
+ else:
1016
+ vision_hidden_states = self.vision_embeddings(pixel_values)
1017
+
1018
+ if self.config.use_pixel_shuffle_proj and getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'pre':
1019
+ vision_hidden_states = self.pixel_shuffle(vision_hidden_states, scale_factor=self.config.downsample_ratio)
1020
+ if self.gradient_checkpointing and self.training:
1021
+ vision_hidden_states = torch.utils.checkpoint.checkpoint(self.pixel_shuffle_proj, vision_hidden_states)
1022
+ else:
1023
+ vision_hidden_states = self.pixel_shuffle_proj(vision_hidden_states)
1024
+
1025
+ hidden_states = self.get_input_embeddings(input_ids)
1026
+ hidden_states = self.replace_img_tokens(input_ids, hidden_states, vision_hidden_states)
1027
+ else:
1028
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
1029
+ else:
1030
+ hidden_states = self.get_input_embeddings(input_ids)
1031
+
1032
+ for layer_idx, layer_module in enumerate(self.encoder):
1033
+ if self.gradient_checkpointing and self.training:
1034
+ assert use_cache is None, 'Gradient checkpointing is not compatible with cache'
1035
+ outputs = torch.utils.checkpoint.checkpoint(layer_module,
1036
+ hidden_states,
1037
+ inference_params,
1038
+ None, False, False,
1039
+ )
1040
+ hidden_states = outputs[0]
1041
+ else:
1042
+ outputs = layer_module(
1043
+ hidden_states=hidden_states,
1044
+ inference_params=inference_params,
1045
+ use_cache=use_cache,
1046
+ )
1047
+ hidden_states = outputs[0]
1048
+
1049
+
1050
+ img_feature = self.get_img_feature(input_ids, hidden_states)
1051
+
1052
+ if self.config.use_pixel_shuffle_proj and getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'post':
1053
+ img_feature = self.pixel_shuffle(img_feature, scale_factor=self.config.downsample_ratio)
1054
+ img_feature = self.pixel_shuffle_proj(img_feature)
1055
+
1056
+ return img_feature, hidden_states
1057
+
1058
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
1059
+ return {
1060
+ layer.layer_idx: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
1061
+ for layer in self.encoder
1062
+ }
1063
+
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]
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
+ }