HongyuanTao commited on
Commit
6cf7380
·
verified ·
1 Parent(s): d391b3c

Upload 17 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",
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":["mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "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
+ "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2",
162
+ "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "mamba2",
163
+ "mamba2", "mamba2", "mamba2", "mamba2", "mamba2", "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())
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:e2f519b0c73a5c075860f8af239613ff0770eceb1da660d906c96665f12ffb5e
3
+ size 4979029664
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f979759cc889a8bfc4ce750ec0bcf207e061b3e3c09543e056391fcfea862751
3
+ size 505005416
model.safetensors.index.json ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5483984896
4
+ },
5
+ "weight_map": {
6
+ "embedding_model.encoder.0.attention.A_log_bias": "model-00001-of-00002.safetensors",
7
+ "embedding_model.encoder.0.attention.conv1d.bias": "model-00001-of-00002.safetensors",
8
+ "embedding_model.encoder.0.attention.conv1d.weight": "model-00001-of-00002.safetensors",
9
+ "embedding_model.encoder.0.attention.dt_bias": "model-00001-of-00002.safetensors",
10
+ "embedding_model.encoder.0.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
11
+ "embedding_model.encoder.0.attention.o_proj.weight": "model-00001-of-00002.safetensors",
12
+ "embedding_model.encoder.0.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
13
+ "embedding_model.encoder.0.attention_norm.weight": "model-00001-of-00002.safetensors",
14
+ "embedding_model.encoder.0.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
15
+ "embedding_model.encoder.0.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
16
+ "embedding_model.encoder.0.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
17
+ "embedding_model.encoder.0.ffn_norm.weight": "model-00001-of-00002.safetensors",
18
+ "embedding_model.encoder.1.attention.A_log_bias": "model-00001-of-00002.safetensors",
19
+ "embedding_model.encoder.1.attention.conv1d.bias": "model-00001-of-00002.safetensors",
20
+ "embedding_model.encoder.1.attention.conv1d.weight": "model-00001-of-00002.safetensors",
21
+ "embedding_model.encoder.1.attention.dt_bias": "model-00001-of-00002.safetensors",
22
+ "embedding_model.encoder.1.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
23
+ "embedding_model.encoder.1.attention.o_proj.weight": "model-00001-of-00002.safetensors",
24
+ "embedding_model.encoder.1.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
25
+ "embedding_model.encoder.1.attention_norm.weight": "model-00001-of-00002.safetensors",
26
+ "embedding_model.encoder.1.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
27
+ "embedding_model.encoder.1.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
28
+ "embedding_model.encoder.1.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
29
+ "embedding_model.encoder.1.ffn_norm.weight": "model-00001-of-00002.safetensors",
30
+ "embedding_model.encoder.2.attention.A_log_bias": "model-00001-of-00002.safetensors",
31
+ "embedding_model.encoder.2.attention.conv1d.bias": "model-00001-of-00002.safetensors",
32
+ "embedding_model.encoder.2.attention.conv1d.weight": "model-00001-of-00002.safetensors",
33
+ "embedding_model.encoder.2.attention.dt_bias": "model-00001-of-00002.safetensors",
34
+ "embedding_model.encoder.2.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
35
+ "embedding_model.encoder.2.attention.o_proj.weight": "model-00001-of-00002.safetensors",
36
+ "embedding_model.encoder.2.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
37
+ "embedding_model.encoder.2.attention_norm.weight": "model-00001-of-00002.safetensors",
38
+ "embedding_model.encoder.2.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
39
+ "embedding_model.encoder.2.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
40
+ "embedding_model.encoder.2.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
41
+ "embedding_model.encoder.2.ffn_norm.weight": "model-00001-of-00002.safetensors",
42
+ "embedding_model.encoder.3.attention.A_log_bias": "model-00001-of-00002.safetensors",
43
+ "embedding_model.encoder.3.attention.conv1d.bias": "model-00001-of-00002.safetensors",
44
+ "embedding_model.encoder.3.attention.conv1d.weight": "model-00001-of-00002.safetensors",
45
+ "embedding_model.encoder.3.attention.dt_bias": "model-00001-of-00002.safetensors",
46
+ "embedding_model.encoder.3.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
47
+ "embedding_model.encoder.3.attention.o_proj.weight": "model-00001-of-00002.safetensors",
48
+ "embedding_model.encoder.3.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
49
+ "embedding_model.encoder.3.attention_norm.weight": "model-00001-of-00002.safetensors",
50
+ "embedding_model.encoder.3.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
51
+ "embedding_model.encoder.3.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
52
+ "embedding_model.encoder.3.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
53
+ "embedding_model.encoder.3.ffn_norm.weight": "model-00001-of-00002.safetensors",
54
+ "embedding_model.encoder.4.attention.A_log_bias": "model-00001-of-00002.safetensors",
55
+ "embedding_model.encoder.4.attention.conv1d.bias": "model-00001-of-00002.safetensors",
56
+ "embedding_model.encoder.4.attention.conv1d.weight": "model-00001-of-00002.safetensors",
57
+ "embedding_model.encoder.4.attention.dt_bias": "model-00001-of-00002.safetensors",
58
+ "embedding_model.encoder.4.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
59
+ "embedding_model.encoder.4.attention.o_proj.weight": "model-00001-of-00002.safetensors",
60
+ "embedding_model.encoder.4.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
61
+ "embedding_model.encoder.4.attention_norm.weight": "model-00001-of-00002.safetensors",
62
+ "embedding_model.encoder.4.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
63
+ "embedding_model.encoder.4.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
64
+ "embedding_model.encoder.4.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
65
+ "embedding_model.encoder.4.ffn_norm.weight": "model-00001-of-00002.safetensors",
66
+ "embedding_model.encoder.5.attention.A_log_bias": "model-00001-of-00002.safetensors",
67
+ "embedding_model.encoder.5.attention.conv1d.bias": "model-00001-of-00002.safetensors",
68
+ "embedding_model.encoder.5.attention.conv1d.weight": "model-00001-of-00002.safetensors",
69
+ "embedding_model.encoder.5.attention.dt_bias": "model-00001-of-00002.safetensors",
70
+ "embedding_model.encoder.5.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
71
+ "embedding_model.encoder.5.attention.o_proj.weight": "model-00001-of-00002.safetensors",
72
+ "embedding_model.encoder.5.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
73
+ "embedding_model.encoder.5.attention_norm.weight": "model-00001-of-00002.safetensors",
74
+ "embedding_model.encoder.5.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
75
+ "embedding_model.encoder.5.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
76
+ "embedding_model.encoder.5.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
77
+ "embedding_model.encoder.5.ffn_norm.weight": "model-00001-of-00002.safetensors",
78
+ "embedding_model.encoder.6.attention.A_log_bias": "model-00001-of-00002.safetensors",
79
+ "embedding_model.encoder.6.attention.conv1d.bias": "model-00001-of-00002.safetensors",
80
+ "embedding_model.encoder.6.attention.conv1d.weight": "model-00001-of-00002.safetensors",
81
+ "embedding_model.encoder.6.attention.dt_bias": "model-00001-of-00002.safetensors",
82
+ "embedding_model.encoder.6.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
83
+ "embedding_model.encoder.6.attention.o_proj.weight": "model-00001-of-00002.safetensors",
84
+ "embedding_model.encoder.6.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
85
+ "embedding_model.encoder.6.attention_norm.weight": "model-00001-of-00002.safetensors",
86
+ "embedding_model.encoder.6.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
87
+ "embedding_model.encoder.6.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
88
+ "embedding_model.encoder.6.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
89
+ "embedding_model.encoder.6.ffn_norm.weight": "model-00001-of-00002.safetensors",
90
+ "embedding_model.encoder.7.attention.A_log_bias": "model-00001-of-00002.safetensors",
91
+ "embedding_model.encoder.7.attention.conv1d.bias": "model-00001-of-00002.safetensors",
92
+ "embedding_model.encoder.7.attention.conv1d.weight": "model-00001-of-00002.safetensors",
93
+ "embedding_model.encoder.7.attention.dt_bias": "model-00001-of-00002.safetensors",
94
+ "embedding_model.encoder.7.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
95
+ "embedding_model.encoder.7.attention.o_proj.weight": "model-00001-of-00002.safetensors",
96
+ "embedding_model.encoder.7.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
97
+ "embedding_model.encoder.7.attention_norm.weight": "model-00001-of-00002.safetensors",
98
+ "embedding_model.encoder.7.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
99
+ "embedding_model.encoder.7.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
100
+ "embedding_model.encoder.7.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
101
+ "embedding_model.encoder.7.ffn_norm.weight": "model-00001-of-00002.safetensors",
102
+ "embedding_model.llm_text_embeddings.weight": "model-00001-of-00002.safetensors",
103
+ "embedding_model.pixel_shuffle_proj.0.bias": "model-00001-of-00002.safetensors",
104
+ "embedding_model.pixel_shuffle_proj.0.weight": "model-00001-of-00002.safetensors",
105
+ "embedding_model.pixel_shuffle_proj.2.bias": "model-00001-of-00002.safetensors",
106
+ "embedding_model.pixel_shuffle_proj.2.weight": "model-00001-of-00002.safetensors",
107
+ "embedding_model.vision_embeddings.class_embedding": "model-00001-of-00002.safetensors",
108
+ "embedding_model.vision_embeddings.patch_embedding.bias": "model-00001-of-00002.safetensors",
109
+ "embedding_model.vision_embeddings.patch_embedding.weight": "model-00001-of-00002.safetensors",
110
+ "embedding_model.vision_embeddings.position_embedding": "model-00001-of-00002.safetensors",
111
+ "language_model.model.layers.0.attention.A_log_bias": "model-00001-of-00002.safetensors",
112
+ "language_model.model.layers.0.attention.conv1d.bias": "model-00001-of-00002.safetensors",
113
+ "language_model.model.layers.0.attention.conv1d.weight": "model-00001-of-00002.safetensors",
114
+ "language_model.model.layers.0.attention.dt_bias": "model-00001-of-00002.safetensors",
115
+ "language_model.model.layers.0.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
116
+ "language_model.model.layers.0.attention.o_proj.weight": "model-00001-of-00002.safetensors",
117
+ "language_model.model.layers.0.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
118
+ "language_model.model.layers.0.attention_norm.weight": "model-00001-of-00002.safetensors",
119
+ "language_model.model.layers.0.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
120
+ "language_model.model.layers.0.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
121
+ "language_model.model.layers.0.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
122
+ "language_model.model.layers.0.ffn_norm.weight": "model-00001-of-00002.safetensors",
123
+ "language_model.model.layers.1.attention.A_log_bias": "model-00001-of-00002.safetensors",
124
+ "language_model.model.layers.1.attention.conv1d.bias": "model-00001-of-00002.safetensors",
125
+ "language_model.model.layers.1.attention.conv1d.weight": "model-00001-of-00002.safetensors",
126
+ "language_model.model.layers.1.attention.dt_bias": "model-00001-of-00002.safetensors",
127
+ "language_model.model.layers.1.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
128
+ "language_model.model.layers.1.attention.o_proj.weight": "model-00001-of-00002.safetensors",
129
+ "language_model.model.layers.1.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
130
+ "language_model.model.layers.1.attention_norm.weight": "model-00001-of-00002.safetensors",
131
+ "language_model.model.layers.1.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
132
+ "language_model.model.layers.1.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
133
+ "language_model.model.layers.1.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
134
+ "language_model.model.layers.1.ffn_norm.weight": "model-00001-of-00002.safetensors",
135
+ "language_model.model.layers.10.attention.A_log_bias": "model-00001-of-00002.safetensors",
136
+ "language_model.model.layers.10.attention.conv1d.bias": "model-00001-of-00002.safetensors",
137
+ "language_model.model.layers.10.attention.conv1d.weight": "model-00001-of-00002.safetensors",
138
+ "language_model.model.layers.10.attention.dt_bias": "model-00001-of-00002.safetensors",
139
+ "language_model.model.layers.10.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
140
+ "language_model.model.layers.10.attention.o_proj.weight": "model-00001-of-00002.safetensors",
141
+ "language_model.model.layers.10.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
142
+ "language_model.model.layers.10.attention_norm.weight": "model-00001-of-00002.safetensors",
143
+ "language_model.model.layers.10.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
144
+ "language_model.model.layers.10.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
145
+ "language_model.model.layers.10.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
146
+ "language_model.model.layers.10.ffn_norm.weight": "model-00001-of-00002.safetensors",
147
+ "language_model.model.layers.11.attention.A_log_bias": "model-00001-of-00002.safetensors",
148
+ "language_model.model.layers.11.attention.conv1d.bias": "model-00001-of-00002.safetensors",
149
+ "language_model.model.layers.11.attention.conv1d.weight": "model-00001-of-00002.safetensors",
150
+ "language_model.model.layers.11.attention.dt_bias": "model-00001-of-00002.safetensors",
151
+ "language_model.model.layers.11.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
152
+ "language_model.model.layers.11.attention.o_proj.weight": "model-00001-of-00002.safetensors",
153
+ "language_model.model.layers.11.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
154
+ "language_model.model.layers.11.attention_norm.weight": "model-00001-of-00002.safetensors",
155
+ "language_model.model.layers.11.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
156
+ "language_model.model.layers.11.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
157
+ "language_model.model.layers.11.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
158
+ "language_model.model.layers.11.ffn_norm.weight": "model-00001-of-00002.safetensors",
159
+ "language_model.model.layers.12.attention.A_log_bias": "model-00001-of-00002.safetensors",
160
+ "language_model.model.layers.12.attention.conv1d.bias": "model-00001-of-00002.safetensors",
161
+ "language_model.model.layers.12.attention.conv1d.weight": "model-00001-of-00002.safetensors",
162
+ "language_model.model.layers.12.attention.dt_bias": "model-00001-of-00002.safetensors",
163
+ "language_model.model.layers.12.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
164
+ "language_model.model.layers.12.attention.o_proj.weight": "model-00001-of-00002.safetensors",
165
+ "language_model.model.layers.12.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
166
+ "language_model.model.layers.12.attention_norm.weight": "model-00001-of-00002.safetensors",
167
+ "language_model.model.layers.12.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
168
+ "language_model.model.layers.12.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
169
+ "language_model.model.layers.12.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
170
+ "language_model.model.layers.12.ffn_norm.weight": "model-00001-of-00002.safetensors",
171
+ "language_model.model.layers.13.attention.A_log_bias": "model-00001-of-00002.safetensors",
172
+ "language_model.model.layers.13.attention.conv1d.bias": "model-00001-of-00002.safetensors",
173
+ "language_model.model.layers.13.attention.conv1d.weight": "model-00001-of-00002.safetensors",
174
+ "language_model.model.layers.13.attention.dt_bias": "model-00001-of-00002.safetensors",
175
+ "language_model.model.layers.13.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
176
+ "language_model.model.layers.13.attention.o_proj.weight": "model-00001-of-00002.safetensors",
177
+ "language_model.model.layers.13.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
178
+ "language_model.model.layers.13.attention_norm.weight": "model-00001-of-00002.safetensors",
179
+ "language_model.model.layers.13.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
180
+ "language_model.model.layers.13.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
181
+ "language_model.model.layers.13.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
182
+ "language_model.model.layers.13.ffn_norm.weight": "model-00001-of-00002.safetensors",
183
+ "language_model.model.layers.14.attention.A_log_bias": "model-00001-of-00002.safetensors",
184
+ "language_model.model.layers.14.attention.conv1d.bias": "model-00001-of-00002.safetensors",
185
+ "language_model.model.layers.14.attention.conv1d.weight": "model-00001-of-00002.safetensors",
186
+ "language_model.model.layers.14.attention.dt_bias": "model-00001-of-00002.safetensors",
187
+ "language_model.model.layers.14.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
188
+ "language_model.model.layers.14.attention.o_proj.weight": "model-00001-of-00002.safetensors",
189
+ "language_model.model.layers.14.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
190
+ "language_model.model.layers.14.attention_norm.weight": "model-00001-of-00002.safetensors",
191
+ "language_model.model.layers.14.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
192
+ "language_model.model.layers.14.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
193
+ "language_model.model.layers.14.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
194
+ "language_model.model.layers.14.ffn_norm.weight": "model-00001-of-00002.safetensors",
195
+ "language_model.model.layers.15.attention.A_log_bias": "model-00001-of-00002.safetensors",
196
+ "language_model.model.layers.15.attention.conv1d.bias": "model-00001-of-00002.safetensors",
197
+ "language_model.model.layers.15.attention.conv1d.weight": "model-00001-of-00002.safetensors",
198
+ "language_model.model.layers.15.attention.dt_bias": "model-00001-of-00002.safetensors",
199
+ "language_model.model.layers.15.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
200
+ "language_model.model.layers.15.attention.o_proj.weight": "model-00001-of-00002.safetensors",
201
+ "language_model.model.layers.15.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
202
+ "language_model.model.layers.15.attention_norm.weight": "model-00001-of-00002.safetensors",
203
+ "language_model.model.layers.15.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
204
+ "language_model.model.layers.15.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
205
+ "language_model.model.layers.15.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
206
+ "language_model.model.layers.15.ffn_norm.weight": "model-00001-of-00002.safetensors",
207
+ "language_model.model.layers.16.attention.A_log_bias": "model-00001-of-00002.safetensors",
208
+ "language_model.model.layers.16.attention.conv1d.bias": "model-00001-of-00002.safetensors",
209
+ "language_model.model.layers.16.attention.conv1d.weight": "model-00001-of-00002.safetensors",
210
+ "language_model.model.layers.16.attention.dt_bias": "model-00001-of-00002.safetensors",
211
+ "language_model.model.layers.16.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
212
+ "language_model.model.layers.16.attention.o_proj.weight": "model-00001-of-00002.safetensors",
213
+ "language_model.model.layers.16.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
214
+ "language_model.model.layers.16.attention_norm.weight": "model-00001-of-00002.safetensors",
215
+ "language_model.model.layers.16.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
216
+ "language_model.model.layers.16.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
217
+ "language_model.model.layers.16.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
218
+ "language_model.model.layers.16.ffn_norm.weight": "model-00001-of-00002.safetensors",
219
+ "language_model.model.layers.17.attention.A_log_bias": "model-00001-of-00002.safetensors",
220
+ "language_model.model.layers.17.attention.conv1d.bias": "model-00001-of-00002.safetensors",
221
+ "language_model.model.layers.17.attention.conv1d.weight": "model-00001-of-00002.safetensors",
222
+ "language_model.model.layers.17.attention.dt_bias": "model-00001-of-00002.safetensors",
223
+ "language_model.model.layers.17.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
224
+ "language_model.model.layers.17.attention.o_proj.weight": "model-00001-of-00002.safetensors",
225
+ "language_model.model.layers.17.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
226
+ "language_model.model.layers.17.attention_norm.weight": "model-00001-of-00002.safetensors",
227
+ "language_model.model.layers.17.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
228
+ "language_model.model.layers.17.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
229
+ "language_model.model.layers.17.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
230
+ "language_model.model.layers.17.ffn_norm.weight": "model-00001-of-00002.safetensors",
231
+ "language_model.model.layers.18.attention.A_log_bias": "model-00001-of-00002.safetensors",
232
+ "language_model.model.layers.18.attention.conv1d.bias": "model-00001-of-00002.safetensors",
233
+ "language_model.model.layers.18.attention.conv1d.weight": "model-00001-of-00002.safetensors",
234
+ "language_model.model.layers.18.attention.dt_bias": "model-00001-of-00002.safetensors",
235
+ "language_model.model.layers.18.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
236
+ "language_model.model.layers.18.attention.o_proj.weight": "model-00001-of-00002.safetensors",
237
+ "language_model.model.layers.18.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
238
+ "language_model.model.layers.18.attention_norm.weight": "model-00001-of-00002.safetensors",
239
+ "language_model.model.layers.18.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
240
+ "language_model.model.layers.18.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
241
+ "language_model.model.layers.18.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
242
+ "language_model.model.layers.18.ffn_norm.weight": "model-00001-of-00002.safetensors",
243
+ "language_model.model.layers.19.attention.A_log_bias": "model-00001-of-00002.safetensors",
244
+ "language_model.model.layers.19.attention.conv1d.bias": "model-00001-of-00002.safetensors",
245
+ "language_model.model.layers.19.attention.conv1d.weight": "model-00001-of-00002.safetensors",
246
+ "language_model.model.layers.19.attention.dt_bias": "model-00001-of-00002.safetensors",
247
+ "language_model.model.layers.19.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
248
+ "language_model.model.layers.19.attention.o_proj.weight": "model-00001-of-00002.safetensors",
249
+ "language_model.model.layers.19.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
250
+ "language_model.model.layers.19.attention_norm.weight": "model-00001-of-00002.safetensors",
251
+ "language_model.model.layers.19.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
252
+ "language_model.model.layers.19.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
253
+ "language_model.model.layers.19.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
254
+ "language_model.model.layers.19.ffn_norm.weight": "model-00001-of-00002.safetensors",
255
+ "language_model.model.layers.2.attention.A_log_bias": "model-00001-of-00002.safetensors",
256
+ "language_model.model.layers.2.attention.conv1d.bias": "model-00001-of-00002.safetensors",
257
+ "language_model.model.layers.2.attention.conv1d.weight": "model-00001-of-00002.safetensors",
258
+ "language_model.model.layers.2.attention.dt_bias": "model-00001-of-00002.safetensors",
259
+ "language_model.model.layers.2.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
260
+ "language_model.model.layers.2.attention.o_proj.weight": "model-00001-of-00002.safetensors",
261
+ "language_model.model.layers.2.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
262
+ "language_model.model.layers.2.attention_norm.weight": "model-00001-of-00002.safetensors",
263
+ "language_model.model.layers.2.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
264
+ "language_model.model.layers.2.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
265
+ "language_model.model.layers.2.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
266
+ "language_model.model.layers.2.ffn_norm.weight": "model-00001-of-00002.safetensors",
267
+ "language_model.model.layers.20.attention.A_log_bias": "model-00001-of-00002.safetensors",
268
+ "language_model.model.layers.20.attention.conv1d.bias": "model-00001-of-00002.safetensors",
269
+ "language_model.model.layers.20.attention.conv1d.weight": "model-00001-of-00002.safetensors",
270
+ "language_model.model.layers.20.attention.dt_bias": "model-00001-of-00002.safetensors",
271
+ "language_model.model.layers.20.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
272
+ "language_model.model.layers.20.attention.o_proj.weight": "model-00001-of-00002.safetensors",
273
+ "language_model.model.layers.20.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
274
+ "language_model.model.layers.20.attention_norm.weight": "model-00001-of-00002.safetensors",
275
+ "language_model.model.layers.20.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
276
+ "language_model.model.layers.20.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
277
+ "language_model.model.layers.20.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
278
+ "language_model.model.layers.20.ffn_norm.weight": "model-00001-of-00002.safetensors",
279
+ "language_model.model.layers.21.attention.A_log_bias": "model-00001-of-00002.safetensors",
280
+ "language_model.model.layers.21.attention.conv1d.bias": "model-00001-of-00002.safetensors",
281
+ "language_model.model.layers.21.attention.conv1d.weight": "model-00001-of-00002.safetensors",
282
+ "language_model.model.layers.21.attention.dt_bias": "model-00001-of-00002.safetensors",
283
+ "language_model.model.layers.21.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
284
+ "language_model.model.layers.21.attention.o_proj.weight": "model-00001-of-00002.safetensors",
285
+ "language_model.model.layers.21.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
286
+ "language_model.model.layers.21.attention_norm.weight": "model-00001-of-00002.safetensors",
287
+ "language_model.model.layers.21.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
288
+ "language_model.model.layers.21.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
289
+ "language_model.model.layers.21.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
290
+ "language_model.model.layers.21.ffn_norm.weight": "model-00001-of-00002.safetensors",
291
+ "language_model.model.layers.22.attention.A_log_bias": "model-00001-of-00002.safetensors",
292
+ "language_model.model.layers.22.attention.conv1d.bias": "model-00001-of-00002.safetensors",
293
+ "language_model.model.layers.22.attention.conv1d.weight": "model-00001-of-00002.safetensors",
294
+ "language_model.model.layers.22.attention.dt_bias": "model-00001-of-00002.safetensors",
295
+ "language_model.model.layers.22.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
296
+ "language_model.model.layers.22.attention.o_proj.weight": "model-00001-of-00002.safetensors",
297
+ "language_model.model.layers.22.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
298
+ "language_model.model.layers.22.attention_norm.weight": "model-00001-of-00002.safetensors",
299
+ "language_model.model.layers.22.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
300
+ "language_model.model.layers.22.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
301
+ "language_model.model.layers.22.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
302
+ "language_model.model.layers.22.ffn_norm.weight": "model-00001-of-00002.safetensors",
303
+ "language_model.model.layers.23.attention.A_log_bias": "model-00001-of-00002.safetensors",
304
+ "language_model.model.layers.23.attention.conv1d.bias": "model-00001-of-00002.safetensors",
305
+ "language_model.model.layers.23.attention.conv1d.weight": "model-00001-of-00002.safetensors",
306
+ "language_model.model.layers.23.attention.dt_bias": "model-00001-of-00002.safetensors",
307
+ "language_model.model.layers.23.attention.g_norm_swish_gate.weight": "model-00002-of-00002.safetensors",
308
+ "language_model.model.layers.23.attention.o_proj.weight": "model-00001-of-00002.safetensors",
309
+ "language_model.model.layers.23.attention.wvkqgdt.weight": "model-00002-of-00002.safetensors",
310
+ "language_model.model.layers.23.attention_norm.weight": "model-00002-of-00002.safetensors",
311
+ "language_model.model.layers.23.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
312
+ "language_model.model.layers.23.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
313
+ "language_model.model.layers.23.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
314
+ "language_model.model.layers.23.ffn_norm.weight": "model-00002-of-00002.safetensors",
315
+ "language_model.model.layers.3.attention.A_log_bias": "model-00001-of-00002.safetensors",
316
+ "language_model.model.layers.3.attention.conv1d.bias": "model-00001-of-00002.safetensors",
317
+ "language_model.model.layers.3.attention.conv1d.weight": "model-00001-of-00002.safetensors",
318
+ "language_model.model.layers.3.attention.dt_bias": "model-00001-of-00002.safetensors",
319
+ "language_model.model.layers.3.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
320
+ "language_model.model.layers.3.attention.o_proj.weight": "model-00001-of-00002.safetensors",
321
+ "language_model.model.layers.3.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
322
+ "language_model.model.layers.3.attention_norm.weight": "model-00001-of-00002.safetensors",
323
+ "language_model.model.layers.3.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
324
+ "language_model.model.layers.3.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
325
+ "language_model.model.layers.3.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
326
+ "language_model.model.layers.3.ffn_norm.weight": "model-00001-of-00002.safetensors",
327
+ "language_model.model.layers.4.attention.A_log_bias": "model-00001-of-00002.safetensors",
328
+ "language_model.model.layers.4.attention.conv1d.bias": "model-00001-of-00002.safetensors",
329
+ "language_model.model.layers.4.attention.conv1d.weight": "model-00001-of-00002.safetensors",
330
+ "language_model.model.layers.4.attention.dt_bias": "model-00001-of-00002.safetensors",
331
+ "language_model.model.layers.4.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
332
+ "language_model.model.layers.4.attention.o_proj.weight": "model-00001-of-00002.safetensors",
333
+ "language_model.model.layers.4.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
334
+ "language_model.model.layers.4.attention_norm.weight": "model-00001-of-00002.safetensors",
335
+ "language_model.model.layers.4.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
336
+ "language_model.model.layers.4.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
337
+ "language_model.model.layers.4.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
338
+ "language_model.model.layers.4.ffn_norm.weight": "model-00001-of-00002.safetensors",
339
+ "language_model.model.layers.5.attention.A_log_bias": "model-00001-of-00002.safetensors",
340
+ "language_model.model.layers.5.attention.conv1d.bias": "model-00001-of-00002.safetensors",
341
+ "language_model.model.layers.5.attention.conv1d.weight": "model-00001-of-00002.safetensors",
342
+ "language_model.model.layers.5.attention.dt_bias": "model-00001-of-00002.safetensors",
343
+ "language_model.model.layers.5.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
344
+ "language_model.model.layers.5.attention.o_proj.weight": "model-00001-of-00002.safetensors",
345
+ "language_model.model.layers.5.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
346
+ "language_model.model.layers.5.attention_norm.weight": "model-00001-of-00002.safetensors",
347
+ "language_model.model.layers.5.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
348
+ "language_model.model.layers.5.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
349
+ "language_model.model.layers.5.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
350
+ "language_model.model.layers.5.ffn_norm.weight": "model-00001-of-00002.safetensors",
351
+ "language_model.model.layers.6.attention.A_log_bias": "model-00001-of-00002.safetensors",
352
+ "language_model.model.layers.6.attention.conv1d.bias": "model-00001-of-00002.safetensors",
353
+ "language_model.model.layers.6.attention.conv1d.weight": "model-00001-of-00002.safetensors",
354
+ "language_model.model.layers.6.attention.dt_bias": "model-00001-of-00002.safetensors",
355
+ "language_model.model.layers.6.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
356
+ "language_model.model.layers.6.attention.o_proj.weight": "model-00001-of-00002.safetensors",
357
+ "language_model.model.layers.6.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
358
+ "language_model.model.layers.6.attention_norm.weight": "model-00001-of-00002.safetensors",
359
+ "language_model.model.layers.6.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
360
+ "language_model.model.layers.6.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
361
+ "language_model.model.layers.6.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
362
+ "language_model.model.layers.6.ffn_norm.weight": "model-00001-of-00002.safetensors",
363
+ "language_model.model.layers.7.attention.A_log_bias": "model-00001-of-00002.safetensors",
364
+ "language_model.model.layers.7.attention.conv1d.bias": "model-00001-of-00002.safetensors",
365
+ "language_model.model.layers.7.attention.conv1d.weight": "model-00001-of-00002.safetensors",
366
+ "language_model.model.layers.7.attention.dt_bias": "model-00001-of-00002.safetensors",
367
+ "language_model.model.layers.7.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
368
+ "language_model.model.layers.7.attention.o_proj.weight": "model-00001-of-00002.safetensors",
369
+ "language_model.model.layers.7.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
370
+ "language_model.model.layers.7.attention_norm.weight": "model-00001-of-00002.safetensors",
371
+ "language_model.model.layers.7.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
372
+ "language_model.model.layers.7.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
373
+ "language_model.model.layers.7.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
374
+ "language_model.model.layers.7.ffn_norm.weight": "model-00001-of-00002.safetensors",
375
+ "language_model.model.layers.8.attention.A_log_bias": "model-00001-of-00002.safetensors",
376
+ "language_model.model.layers.8.attention.conv1d.bias": "model-00001-of-00002.safetensors",
377
+ "language_model.model.layers.8.attention.conv1d.weight": "model-00001-of-00002.safetensors",
378
+ "language_model.model.layers.8.attention.dt_bias": "model-00001-of-00002.safetensors",
379
+ "language_model.model.layers.8.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
380
+ "language_model.model.layers.8.attention.o_proj.weight": "model-00001-of-00002.safetensors",
381
+ "language_model.model.layers.8.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
382
+ "language_model.model.layers.8.attention_norm.weight": "model-00001-of-00002.safetensors",
383
+ "language_model.model.layers.8.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
384
+ "language_model.model.layers.8.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
385
+ "language_model.model.layers.8.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
386
+ "language_model.model.layers.8.ffn_norm.weight": "model-00001-of-00002.safetensors",
387
+ "language_model.model.layers.9.attention.A_log_bias": "model-00001-of-00002.safetensors",
388
+ "language_model.model.layers.9.attention.conv1d.bias": "model-00001-of-00002.safetensors",
389
+ "language_model.model.layers.9.attention.conv1d.weight": "model-00001-of-00002.safetensors",
390
+ "language_model.model.layers.9.attention.dt_bias": "model-00001-of-00002.safetensors",
391
+ "language_model.model.layers.9.attention.g_norm_swish_gate.weight": "model-00001-of-00002.safetensors",
392
+ "language_model.model.layers.9.attention.o_proj.weight": "model-00001-of-00002.safetensors",
393
+ "language_model.model.layers.9.attention.wvkqgdt.weight": "model-00001-of-00002.safetensors",
394
+ "language_model.model.layers.9.attention_norm.weight": "model-00001-of-00002.safetensors",
395
+ "language_model.model.layers.9.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
396
+ "language_model.model.layers.9.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
397
+ "language_model.model.layers.9.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
398
+ "language_model.model.layers.9.ffn_norm.weight": "model-00001-of-00002.safetensors",
399
+ "language_model.model.norm.weight": "model-00002-of-00002.safetensors",
400
+ "language_model.model.tok_embeddings.weight": "model-00001-of-00002.safetensors",
401
+ "language_model.output.weight": "model-00002-of-00002.safetensors"
402
+ }
403
+ }
modeling_mmMamba.py ADDED
@@ -0,0 +1,1136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ class mmMambaMLP(nn.Module):
134
+ def __init__(self, config):
135
+ super().__init__()
136
+ self.config = config
137
+ self.hidden_size = config.hidden_size
138
+ self.intermediate_size = config.intermediate_size
139
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
140
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
141
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
142
+ self.act_fn = ACT2FN[config.hidden_act]
143
+
144
+ def forward(self, x):
145
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
146
+
147
+ return down_proj
148
+
149
+
150
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
151
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
152
+ """
153
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
154
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
155
+ """
156
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
157
+ if n_rep == 1:
158
+ return hidden_states
159
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
160
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
161
+
162
+ def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
163
+ """
164
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
165
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
166
+ """
167
+ batch, num_key_value_heads, head_dim = hidden_states.shape
168
+ if n_rep == 1:
169
+ return hidden_states
170
+ hidden_states = hidden_states[:, :, None, :].expand(batch, num_key_value_heads, n_rep, head_dim)
171
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, head_dim)
172
+
173
+
174
+ class MHA_LM(nn.Module):
175
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
176
+
177
+ def __init__(self, config: mmMambaConfig, layer_idx: int):
178
+ super().__init__()
179
+ self.config = config
180
+ self.layer_idx = layer_idx#-------------------------
181
+ self.hidden_size = config.hidden_size
182
+ self.num_heads = config.num_attention_heads
183
+ self.head_dim = self.hidden_size // self.num_heads
184
+ self.num_key_value_heads = config.num_key_value_heads
185
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
186
+ self.max_position_embeddings = config.max_position_embeddings
187
+ self.is_causal = True
188
+ self.rotary_emb_dim = self.head_dim
189
+ self.softmax_scale = None
190
+ self.causal = True
191
+
192
+ if (self.head_dim * self.num_heads) != self.hidden_size:
193
+ raise ValueError(
194
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
195
+ f" and `num_heads`: {self.num_heads})."
196
+ )
197
+
198
+ self.wqkv = nn.Linear(
199
+ self.hidden_size,
200
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
201
+ bias=False,
202
+ )
203
+
204
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
205
+ self.rotary_emb = RotaryEmbedding(
206
+ self.head_dim,
207
+ base=self.config.rope_theta,
208
+ interleaved=False,
209
+ device=self.wo.weight.device,
210
+ )
211
+
212
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
213
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
214
+
215
+ def _update_kv_cache(self, kv, inference_params):
216
+ """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)"""
217
+ assert self.layer_idx is not None, "Generation requires layer_idx in the constructor"
218
+ return _update_kv_cache(kv, inference_params, self.layer_idx)
219
+
220
+ def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params):
221
+ """
222
+ Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention.
223
+ q: (batch_size, seqlen_q, nheads, head_dim)
224
+ kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim)
225
+ """
226
+ assert inference_params is not None and inference_params.seqlen_offset > 0
227
+ if self.rotary_emb_dim > 0:
228
+ self.rotary_emb._update_cos_sin_cache(
229
+ inference_params.max_seqlen, device=q.device, dtype=q.dtype
230
+ )
231
+ rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached
232
+ else:
233
+ rotary_cos, rotary_sin = None, None
234
+ batch = q.shape[0]
235
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
236
+ kv_cache = kv_cache[:batch]
237
+ cache_seqlens = (
238
+ inference_params.lengths_per_sample[:batch]
239
+ if inference_params.lengths_per_sample is not None
240
+ else inference_params.seqlen_offset
241
+ )
242
+ assert flash_attn_with_kvcache is not None, "flash_attn must be installed"
243
+ context = flash_attn_with_kvcache(
244
+ q,
245
+ kv_cache[:, :, 0],
246
+ kv_cache[:, :, 1],
247
+ kv[:, :, 0],
248
+ kv[:, :, 1],
249
+ rotary_cos=rotary_cos,
250
+ rotary_sin=rotary_sin,
251
+ cache_seqlens=cache_seqlens,
252
+ softmax_scale=self.softmax_scale,
253
+ causal=self.causal,
254
+ rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False,
255
+ )
256
+ return context
257
+
258
+ def _update_kvcache_attention(self, q, kv, inference_params):
259
+ """Write kv to inference_params, then do attention"""
260
+ if (
261
+ inference_params.seqlen_offset == 0
262
+ or flash_attn_with_kvcache is None
263
+ ):
264
+ # TODO: this only uses seqlen_offset and not lengths_per_sample.
265
+ kv = self._update_kv_cache(kv, inference_params)
266
+ k, v = kv.unbind(dim=-3)
267
+ #k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
268
+ #v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
269
+ attn_output = flash_attn_func(
270
+ q, k, v, 0.0, softmax_scale=None, causal=self.causal
271
+ )
272
+ return attn_output
273
+ else:
274
+ batch = q.shape[0]
275
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
276
+ kv_cache = kv_cache[:batch]
277
+ cache_seqlens = (
278
+ inference_params.lengths_per_sample[:batch]
279
+ if inference_params.lengths_per_sample is not None
280
+ else inference_params.seqlen_offset
281
+ )
282
+ return flash_attn_with_kvcache(
283
+ q,
284
+ kv_cache[:, :, 0],
285
+ kv_cache[:, :, 1],
286
+ kv[:, :, 0],
287
+ kv[:, :, 1],
288
+ cache_seqlens=cache_seqlens,
289
+ softmax_scale=self.softmax_scale,
290
+ causal=self.causal,
291
+ )
292
+
293
+ def forward(
294
+ self,
295
+ hidden_states: torch.Tensor,
296
+ inference_params = None,
297
+ output_attentions: bool = False,
298
+ cache_position: Optional[torch.LongTensor] = None,#------------------------------------------------------------------------
299
+ use_cache: bool = False,
300
+ **kwargs,
301
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
302
+ if inference_params is not None and self.layer_idx not in inference_params.key_value_memory_dict:
303
+ inference_params.key_value_memory_dict[self.layer_idx] = self.allocate_inference_cache(
304
+ hidden_states.shape[0], inference_params.max_seqlen, dtype=hidden_states.dtype
305
+ )
306
+ seqlen_offset = (
307
+ 0
308
+ if inference_params is None
309
+ else (
310
+ inference_params.lengths_per_sample
311
+ if inference_params.lengths_per_sample is not None
312
+ else inference_params.seqlen_offset
313
+ )
314
+ )
315
+
316
+ bsz, q_len, _ = hidden_states.size()
317
+ rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None
318
+
319
+ qkv = self.wqkv(hidden_states)
320
+ qkv = rearrange(
321
+ qkv,
322
+ "b q (h gs d) -> b q h gs d",
323
+ gs=2 + self.num_key_value_groups,
324
+ d=self.head_dim,
325
+ )
326
+
327
+ q = qkv[..., : self.num_key_value_groups, :]
328
+ q = rearrange(q, "b q h gs d -> b q (h gs) d")
329
+ kv = qkv[..., self.num_key_value_groups:, :].transpose(2,3)
330
+
331
+ if (
332
+ inference_params is None
333
+ or inference_params.seqlen_offset == 0
334
+ or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0)
335
+ ):
336
+ if self.rotary_emb_dim > 0:
337
+ q, kv = self.rotary_emb(
338
+ q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen
339
+ )
340
+ if inference_params is None:
341
+ k, v = kv.unbind(dim=-3)
342
+ k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
343
+ v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
344
+ context = F.scaled_dot_product_attention(
345
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, scale=None
346
+ ).transpose(1, 2)
347
+ else:
348
+ context = self._update_kvcache_attention(q, kv, inference_params)
349
+ else:
350
+ context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params)
351
+ context = rearrange(context, "... h d -> ... (h d)")
352
+ out = self.wo(context)
353
+ return out
354
+
355
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None):
356
+ dtype = self.wo.weight.dtype if dtype is None else dtype
357
+ device = self.wo.weight.device
358
+ kv_cache = torch.empty(
359
+ batch_size, max_seqlen, 2, self.num_key_value_heads, self.head_dim, dtype=dtype, device=device,
360
+ )
361
+ return kv_cache, None
362
+
363
+
364
+ class Mamba2_LM(nn.Module):
365
+ """
366
+ LoLCATs attention implementation initialized from a
367
+ `LlamaAttention` or `MistralAttention` object (base_attn)
368
+
369
+ Most of the arguments are directly tied to argparse args
370
+ - For now we don't support padding.
371
+ """
372
+ def __init__(self, config: mmMambaConfig, layer_idx: Optional[int] = None,
373
+ elementwise_affine: Optional[bool] = True,
374
+ norm_eps: float = 1e-5,
375
+ ):
376
+ super().__init__()
377
+ self.config = config
378
+ self.hidden_size = config.hidden_size
379
+ self.num_heads = config.num_attention_heads
380
+ self.head_dim = self.hidden_size // self.num_heads
381
+ self.num_key_value_heads = config.num_key_value_heads
382
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
383
+ self.max_position_embeddings = config.max_position_embeddings
384
+ self.layer_idx = layer_idx
385
+ self.bias = False
386
+ self.chunk_size = 128
387
+ conv_bias = True
388
+ self.conv_bias = conv_bias
389
+ self.d_conv = 2
390
+ self.activation="silu"
391
+ self.max_position_embeddings = config.max_position_embeddings
392
+ self.rope_theta = config.rope_theta
393
+
394
+ self.wvkqgdt = nn.Linear(
395
+ self.hidden_size,
396
+ (self.num_heads + 2 * self.num_key_value_heads + self.num_heads) * self.head_dim + self.num_heads,
397
+ bias=self.bias
398
+ )
399
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
400
+
401
+ self.device = self.wvkqgdt.weight.device
402
+ self.dtype = self.wvkqgdt.weight.dtype
403
+
404
+ conv_dim = self.num_heads * self.head_dim + 2 * self.num_key_value_heads * self.head_dim
405
+
406
+ self.conv1d = nn.Conv1d(
407
+ in_channels=conv_dim,
408
+ out_channels=conv_dim,
409
+ bias=self.conv_bias,
410
+ kernel_size=self.d_conv,
411
+ groups=conv_dim,
412
+ padding=self.d_conv - 1,
413
+ device=self.device,
414
+ dtype=self.dtype
415
+ )
416
+ with torch.no_grad():
417
+ self.conv1d.weight.zero_()
418
+ self.conv1d.weight[:, 0, 1] = 1
419
+ self.conv1d.bias.zero_()
420
+
421
+ # Activation after conv
422
+ if self.activation == "identity":
423
+ self.act = nn.Identity()
424
+ elif self.activation in ["silu", "swish"]:
425
+ self.act = nn.SiLU()
426
+ else:
427
+ raise ValueError(f"Unknown activation {self.activation}")
428
+
429
+ self.g_norm_swish_gate = FusedRMSNormSwishGate(hidden_size=self.head_dim, elementwise_affine=elementwise_affine, eps=norm_eps).to(self.dtype).to(self.device)
430
+
431
+ dt = torch.exp(
432
+ torch.rand(self.num_heads, dtype=self.dtype, device=self.device) * (math.log(0.1) - math.log(0.001))
433
+ + math.log(0.001)
434
+ )
435
+ dt = torch.clamp(dt, min=0.001)
436
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
437
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
438
+ self.dt_bias = nn.Parameter(inv_dt)
439
+ self.dt_bias._no_weight_decay = True
440
+
441
+ A_log_bias = torch.zeros(self.num_heads, dtype=self.dtype, device=self.device)
442
+ self.A_log_bias = nn.Parameter(A_log_bias)
443
+ self.A_log_bias._no_weight_decay = True
444
+
445
+ def forward(self,
446
+ hidden_states: torch.Tensor,
447
+ inference_params = None,
448
+ output_attentions: bool = False,
449
+ use_cache: bool = True,
450
+ **kwargs,
451
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
452
+ hidden_states = hidden_states.to(self.dtype)
453
+ vkqgdt = self.wvkqgdt(hidden_states)
454
+ vkq, g, dt = torch.split(
455
+ vkqgdt,
456
+ [
457
+ (2*self.num_key_value_heads+self.num_heads) * self.head_dim,
458
+ self.num_heads * self.head_dim,
459
+ self.num_heads,
460
+ ],
461
+ dim=2,
462
+ )
463
+ batch, seqlen, _ = hidden_states.shape
464
+ conv_state, ssm_state = None, None
465
+ if inference_params is not None:
466
+ conv_state, ssm_state = self._get_states_from_cache(inference_params, batch)
467
+
468
+ if use_cache and inference_params.seqlen_offset==0:
469
+ vkq, new_conv_states = causal_conv1d_fn(
470
+ vkq.transpose(1, 2),
471
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
472
+ self.conv1d.bias,
473
+ initial_states=None,
474
+ return_final_states=True,
475
+ activation=None if self.activation == "identity" else self.activation,
476
+ )
477
+
478
+ v, k, q = torch.split(
479
+ vkq,
480
+ [
481
+ self.num_key_value_heads * self.head_dim,
482
+ self.num_key_value_heads * self.head_dim,
483
+ self.num_heads * self.head_dim,
484
+ ],
485
+ dim=1,
486
+ )
487
+
488
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
489
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
490
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
491
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
492
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
493
+
494
+ A = -torch.exp(self.A_log_bias.float())
495
+
496
+ y, new_ssm_states = mamba_chunk_scan_combined(
497
+ x = v,
498
+ #x = v / F.softplus(A_log).to(v.dtype).unsqueeze(-1),
499
+ dt=dt,
500
+ dt_softplus=True,
501
+ A=A,
502
+ B=k,
503
+ C=q,
504
+ chunk_size=self.chunk_size,
505
+ dt_bias=self.dt_bias,
506
+ initial_states=None, # currently not supported by mamba_ssm.utils.generation
507
+ return_final_states=True,
508
+ )
509
+
510
+ conv_state.copy_(new_conv_states)
511
+ ssm_state.copy_(new_ssm_states)
512
+
513
+ elif use_cache and inference_params.seqlen_offset>0:
514
+
515
+ vkq = causal_conv1d_update(
516
+ vkq.transpose(1, 2).squeeze(-1),
517
+ conv_state,
518
+ self.conv1d.weight.squeeze(1),
519
+ self.conv1d.bias,
520
+ self.activation,
521
+ )
522
+
523
+ v, k, q = torch.split(
524
+ vkq,
525
+ [
526
+ self.num_key_value_heads * self.head_dim,
527
+ self.num_key_value_heads * self.head_dim,
528
+ self.num_heads * self.head_dim,
529
+ ],
530
+ dim=1,
531
+ )
532
+
533
+ v = rearrange(v, "b (h n) -> b h n", h=self.num_key_value_heads)
534
+ k = rearrange(k, "b (h n) -> b h n", h=self.num_key_value_heads)
535
+ q = rearrange(q, "b (h n) -> b h n", h=self.num_heads)
536
+ k = repeat_kv2(k, self.num_key_value_groups)
537
+ v = repeat_kv2(v, self.num_key_value_groups)
538
+
539
+ dt = dt.transpose(1, 2).squeeze(-1)
540
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
541
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
542
+ A = -torch.exp(self.A_log_bias.float())
543
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.head_dim).to(dtype=torch.float32)
544
+ D = torch.zeros((self.num_heads, self.head_dim), dtype=A.dtype, device=A.device)
545
+
546
+ y = selective_state_update(
547
+ ssm_state,
548
+ v,
549
+ dt,
550
+ A=A,
551
+ B=k,
552
+ C=q,
553
+ D=D,
554
+ dt_bias=dt_bias,
555
+ dt_softplus=True,
556
+ )
557
+
558
+ else:
559
+ vkq = causal_conv1d_fn(
560
+ vkq.transpose(1, 2),
561
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
562
+ self.conv1d.bias,
563
+ initial_states=None,
564
+ return_final_states=False,
565
+ activation=None if self.activation == "identity" else self.activation,
566
+ )
567
+
568
+ v, k, q = torch.split(
569
+ vkq,
570
+ [
571
+ self.num_key_value_heads * self.head_dim,
572
+ self.num_key_value_heads * self.head_dim,
573
+ self.num_heads * self.head_dim,
574
+ ],
575
+ dim=1,
576
+ )
577
+
578
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
579
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
580
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
581
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
582
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
583
+
584
+ A = -torch.exp(self.A_log_bias.float())
585
+
586
+ y = mamba_chunk_scan_combined(
587
+ x = v,
588
+ dt=dt,
589
+ dt_softplus=True,
590
+ A=A,
591
+ B=k,
592
+ C=q,
593
+ chunk_size=self.chunk_size,
594
+ dt_bias=self.dt_bias,
595
+ initial_states=None, # currently not supported by mamba_ssm.utils.generation
596
+ return_final_states=False,
597
+ )
598
+
599
+ g = rearrange(g, 'b l (h d) -> b l h d', h=self.num_heads)
600
+ y_true = self.g_norm_swish_gate(y, g)
601
+ y_true = y_true.view(batch, seqlen, self.hidden_size)
602
+ y_true = self.o_proj(y_true)
603
+
604
+ return y_true
605
+
606
+ def _get_states_from_cache(self, inference_params, batch_size, initialize_states=False):
607
+ device = self.conv1d.weight.device
608
+ dtype = self.conv1d.weight.dtype
609
+ assert self.layer_idx is not None
610
+ if self.layer_idx not in inference_params.key_value_memory_dict:
611
+ batch_shape = (batch_size,)
612
+ conv_state = torch.zeros(
613
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
614
+ )
615
+ ssm_state = torch.zeros(
616
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
617
+ )
618
+ inference_params.key_value_memory_dict[self.layer_idx] = (conv_state, ssm_state)
619
+ else:
620
+ conv_state, ssm_state = inference_params.key_value_memory_dict[self.layer_idx]
621
+ # TODO: What if batch size changes between generation, and we reuse the same states?
622
+ if initialize_states:
623
+ conv_state.zero_()
624
+ ssm_state.zero_()
625
+ return conv_state, ssm_state
626
+
627
+
628
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
629
+ device = self.conv1d.weight.device
630
+ dtype = self.conv1d.weight.dtype
631
+ conv_state = torch.zeros(
632
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
633
+ )
634
+
635
+ ssm_state = torch.zeros(
636
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
637
+ )
638
+ return conv_state, ssm_state
639
+
640
+
641
+ mmMamba_ATTENTION_CLASSES = {
642
+ 'mha': MHA_LM,
643
+ "mamba2":Mamba2_LM
644
+ }
645
+
646
+
647
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
648
+ class mmMambaDecoderLayer(nn.Module):
649
+ def __init__(self, config: mmMambaConfig, layer_idx: int):
650
+ super().__init__()
651
+ self.hidden_size = config.hidden_size
652
+ self.layer_idx = layer_idx
653
+ self.attention = mmMamba_ATTENTION_CLASSES[config.layers_block_type[layer_idx-8]](config=config, layer_idx=layer_idx)
654
+
655
+ self.feed_forward = mmMambaMLP(config)
656
+ self.attention_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
657
+ self.ffn_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
658
+
659
+
660
+ def forward(
661
+ self,
662
+ hidden_states: torch.Tensor,
663
+ inference_params = None,
664
+ output_attentions: Optional[bool] = False,
665
+ use_cache: Optional[bool] = True,
666
+ **kwargs,
667
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
668
+ """
669
+ Args:
670
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
671
+ output_attentions (`bool`, *optional*):
672
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
673
+ returned tensors for more detail.
674
+ use_cache (`bool`, *optional*):
675
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
676
+ (see `past_key_values`).
677
+ """
678
+ #start_time = time.time()
679
+ residual = hidden_states
680
+
681
+ hidden_states = self.attention_norm(hidden_states)
682
+
683
+ # Self Attention
684
+ hidden_states = self.attention(
685
+ hidden_states=hidden_states,
686
+ inference_params=inference_params,
687
+ output_attentions=output_attentions,
688
+ use_cache=use_cache,
689
+ **kwargs,
690
+ )
691
+ hidden_states = residual + hidden_states
692
+
693
+ # Fully Connected
694
+ residual = hidden_states
695
+ hidden_states = self.ffn_norm(hidden_states)
696
+ hidden_states = self.feed_forward(hidden_states)
697
+ hidden_states = residual + hidden_states
698
+
699
+
700
+ outputs = (hidden_states,)
701
+
702
+ if output_attentions:
703
+ outputs += self_attn_weights
704
+
705
+ #end_time = time.time()
706
+ #print("language_model_time:", end_time-start_time)
707
+ return outputs
708
+
709
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
710
+ return self.attention.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
711
+
712
+
713
+ mmMamba_START_DOCSTRING = r"""
714
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
715
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
716
+ etc.)
717
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
718
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
719
+ and behavior.
720
+ Parameters:
721
+ config ([`mmMambaConfig`]):
722
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
723
+ load the weights associated with the model, only the configuration. Check out the
724
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
725
+ """
726
+
727
+
728
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->mmMamba
729
+ @add_start_docstrings(
730
+ 'The bare mmMamba Model outputting raw hidden-states without any specific head on top.',
731
+ mmMamba_START_DOCSTRING,
732
+ )
733
+ class mmMambaPreTrainedModel(PreTrainedModel):
734
+ config_class = mmMambaConfig
735
+ base_model_prefix = 'model'
736
+ supports_gradient_checkpointing = True
737
+ _no_split_modules = ['mmMambaDecoderLayer']
738
+ _skip_keys_device_placement = 'past_key_values'
739
+ _supports_flash_attn_2 = True
740
+
741
+ def _init_weights(self, module):
742
+ std = self.config.initializer_range
743
+ if isinstance(module, nn.Linear):
744
+ module.weight.data.normal_(mean=0.0, std=std)
745
+ if module.bias is not None:
746
+ module.bias.data.zero_()
747
+ elif isinstance(module, nn.Embedding):
748
+ module.weight.data.normal_(mean=0.0, std=std)
749
+ if module.padding_idx is not None:
750
+ module.weight.data[module.padding_idx].zero_()
751
+
752
+
753
+ mmMamba_INPUTS_DOCSTRING = r"""
754
+ Args:
755
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
756
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
757
+ it.
758
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
759
+ [`PreTrainedTokenizer.__call__`] for details.
760
+ [What are input IDs?](../glossary#input-ids)
761
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
762
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
763
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
764
+ model's internal embedding lookup matrix.
765
+ use_cache (`bool`, *optional*):
766
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
767
+ `past_key_values`).
768
+ output_attentions (`bool`, *optional*):
769
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
770
+ tensors for more detail.
771
+ output_hidden_states (`bool`, *optional*):
772
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
773
+ more detail.
774
+ return_dict (`bool`, *optional*):
775
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
776
+ """
777
+
778
+
779
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
780
+ @add_start_docstrings(
781
+ 'The bare mmMamba Model outputting raw hidden-states without any specific head on top.',
782
+ mmMamba_START_DOCSTRING,
783
+ )
784
+ class mmMambaModel(mmMambaPreTrainedModel):
785
+ """
786
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`mmMambaDecoderLayer`]
787
+ Args:
788
+ config: mmMambaConfig
789
+ """
790
+
791
+ _auto_class = 'AutoModel'
792
+
793
+ def __init__(self, config: mmMambaConfig):
794
+ super().__init__(config)
795
+ self.padding_idx = config.pad_token_id
796
+ self.vocab_size = config.vocab_size
797
+ self.config = config
798
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
799
+
800
+ self.layers = nn.ModuleList([mmMambaDecoderLayer(config, (layer_idx+8)) for layer_idx in range(config.num_hidden_layers)])
801
+ self.norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
802
+
803
+ self.gradient_checkpointing = False
804
+ # Initialize weights and apply final processing
805
+ self.post_init()
806
+
807
+ def get_input_embeddings(self):
808
+ return self.tok_embeddings
809
+
810
+ def set_input_embeddings(self, value):
811
+ self.tok_embeddings = value
812
+
813
+ @add_start_docstrings_to_model_forward(mmMamba_INPUTS_DOCSTRING)
814
+ def forward(
815
+ self,
816
+ input_ids: torch.LongTensor = None,
817
+ inference_params=None,
818
+ inputs_embeds: Optional[torch.FloatTensor] = None,
819
+ use_cache: Optional[bool] = True,
820
+ output_attentions: Optional[bool] = None,
821
+ output_hidden_states: Optional[bool] = None,
822
+ return_dict: Optional[bool] = None,
823
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
824
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
825
+ output_hidden_states = (
826
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
827
+ )
828
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
829
+
830
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
831
+
832
+ if self.config.attn_implementation == 'flash_attention_2':
833
+ _import_flash_attn()
834
+
835
+ # retrieve input_ids and inputs_embeds
836
+ if input_ids is not None and inputs_embeds is not None:
837
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
838
+ elif input_ids is not None:
839
+ batch_size, seq_length = input_ids.shape[:2]
840
+ elif inputs_embeds is not None:
841
+ batch_size, seq_length = inputs_embeds.shape[:2]
842
+ else:
843
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
844
+
845
+ if inputs_embeds is None:
846
+ inputs_embeds = self.tok_embeddings(input_ids)
847
+
848
+ # embed positions
849
+ hidden_states = inputs_embeds
850
+
851
+ if self.gradient_checkpointing and self.training:
852
+ if use_cache:
853
+ logger.warning_once(
854
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
855
+ )
856
+ use_cache = False
857
+
858
+ # decoder layers
859
+ all_hidden_states = () if output_hidden_states else None
860
+ all_self_attns = () if output_attentions else None
861
+ next_decoder_cache = () if use_cache else None
862
+
863
+ for idx, decoder_layer in enumerate(self.layers):
864
+ if output_hidden_states:
865
+ all_hidden_states += (hidden_states,)
866
+
867
+ if self.gradient_checkpointing and self.training:
868
+
869
+ def create_custom_forward(module):
870
+ def custom_forward(*inputs):
871
+ # None for past_key_value
872
+ return module(*inputs, output_attentions, None)
873
+
874
+ return custom_forward
875
+
876
+ layer_outputs = torch.utils.checkpoint.checkpoint(
877
+ create_custom_forward(decoder_layer),
878
+ hidden_states,
879
+ inference_params,
880
+ None,
881
+ )
882
+ else:
883
+ layer_outputs = decoder_layer(
884
+ hidden_states,
885
+ inference_params=inference_params,
886
+ output_attentions=output_attentions,
887
+ use_cache=use_cache,
888
+ )
889
+
890
+ hidden_states = layer_outputs[0]
891
+
892
+
893
+ if output_attentions:
894
+ all_self_attns += layer_outputs[1]
895
+
896
+ hidden_states = self.norm(hidden_states)
897
+
898
+ # add hidden states from the last decoder layer
899
+ if output_hidden_states:
900
+ all_hidden_states += (hidden_states,)
901
+
902
+ next_cache = None
903
+ if not return_dict:
904
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
905
+ return BaseModelOutputWithPast(
906
+ last_hidden_state=hidden_states,
907
+ past_key_values=next_cache,
908
+ hidden_states=all_hidden_states,
909
+ attentions=all_self_attns,
910
+ )
911
+
912
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
913
+ return {
914
+ layer.layer_idx: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
915
+ for layer in self.layers
916
+ }
917
+
918
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
919
+ class mmMambaForCausalLM(mmMambaPreTrainedModel):
920
+ _auto_class = 'AutoModelForCausalLM'
921
+
922
+ _tied_weights_keys = ['output.weight']
923
+
924
+ def __init__(self, config):
925
+ super().__init__(config)
926
+ self.model = mmMambaModel(config)
927
+ self.vocab_size = config.vocab_size
928
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
929
+
930
+ # Initialize weights and apply final processing
931
+ self.post_init()
932
+
933
+ def get_input_embeddings(self):
934
+ return self.model.tok_embeddings
935
+
936
+ def set_input_embeddings(self, value):
937
+ self.model.tok_embeddings = value
938
+
939
+ def get_output_embeddings(self):
940
+ return self.output
941
+
942
+ def set_output_embeddings(self, new_embeddings):
943
+ self.output = new_embeddings
944
+
945
+ def set_decoder(self, decoder):
946
+ self.model = decoder
947
+
948
+ def get_decoder(self):
949
+ return self.model
950
+
951
+ @add_start_docstrings_to_model_forward(mmMamba_INPUTS_DOCSTRING)
952
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
953
+ def forward(
954
+ self,
955
+ input_ids: torch.LongTensor = None,
956
+ inference_params=None,
957
+ num_last_tokens=0,
958
+ inputs_embeds: Optional[torch.FloatTensor] = None,
959
+ labels: Optional[torch.LongTensor] = None,
960
+ use_cache: Optional[bool] = True,
961
+ output_attentions: Optional[bool] = None,
962
+ output_hidden_states: Optional[bool] = None,
963
+ return_dict: Optional[bool] = None,
964
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
965
+ r"""
966
+ Args:
967
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
968
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
969
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
970
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
971
+ Returns:
972
+ Example:
973
+ ```python
974
+ >>> from transformers import AutoTokenizer, mmMambaForCausalLM
975
+ >>> model = mmMambaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
976
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
977
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
978
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
979
+ >>> # Generate
980
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
981
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
982
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
983
+ ```"""
984
+
985
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
986
+ output_hidden_states = (
987
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
988
+ )
989
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
990
+
991
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
992
+ outputs = self.model(
993
+ input_ids=input_ids,
994
+ inference_params=inference_params,
995
+ inputs_embeds=inputs_embeds,
996
+ use_cache=use_cache,
997
+ output_attentions=output_attentions,
998
+ output_hidden_states=output_hidden_states,
999
+ return_dict=return_dict,
1000
+ )
1001
+
1002
+ hidden_states = outputs[0]
1003
+
1004
+ if num_last_tokens > 0:
1005
+ hidden_states = hidden_states[:, -num_last_tokens:]
1006
+
1007
+ logits = self.output(hidden_states)
1008
+ logits = logits.float()
1009
+
1010
+ loss = None
1011
+ if labels is not None:
1012
+ # Shift so that tokens < n predict n
1013
+ shift_logits = logits[..., :-1, :].contiguous()
1014
+ shift_labels = labels[..., 1:].contiguous()
1015
+ # Flatten the tokens
1016
+ loss_fct = CrossEntropyLoss()
1017
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1018
+ shift_labels = shift_labels.view(-1)
1019
+ # Enable model parallelism
1020
+ shift_labels = shift_labels.to(shift_logits.device)
1021
+ loss = loss_fct(shift_logits, shift_labels)
1022
+
1023
+ if not return_dict:
1024
+ output = (logits,) + outputs[1:]
1025
+ return (loss,) + output if loss is not None else output
1026
+
1027
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1028
+ output = CausalLMOutputWithPast(
1029
+ loss=loss,
1030
+ logits=logits,
1031
+ past_key_values=outputs.past_key_values,
1032
+ hidden_states=outputs.hidden_states,
1033
+ attentions=outputs.attentions,
1034
+ )
1035
+ output['logits'] = output['logits'].to(device)
1036
+ return output
1037
+
1038
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
1039
+ return self.model.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
1040
+
1041
+ @staticmethod
1042
+ def _reorder_cache(past_key_values, beam_idx):
1043
+ reordered_past = ()
1044
+ for layer_past in past_key_values:
1045
+ reordered_past += (
1046
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1047
+ )
1048
+ return reordered_past
1049
+
1050
+
1051
+ @torch.no_grad()
1052
+ def stream_chat(
1053
+ self,
1054
+ tokenizer,
1055
+ query: str,
1056
+ history: List[Tuple[str, str]] = [],
1057
+ max_new_tokens: int = 1024,
1058
+ do_sample: bool = True,
1059
+ temperature: float = 0.8,
1060
+ top_p: float = 0.8,
1061
+ **kwargs,
1062
+ ):
1063
+ """
1064
+ Return a generator in format: (response, history)
1065
+ Eg.
1066
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1067
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1068
+ """
1069
+ if BaseStreamer is None:
1070
+ raise ModuleNotFoundError(
1071
+ 'The version of `transformers` is too low. Please make sure '
1072
+ 'that you have installed `transformers>=4.28.0`.'
1073
+ )
1074
+
1075
+ response_queue = queue.Queue(maxsize=20)
1076
+
1077
+ class ChatStreamer(BaseStreamer):
1078
+ def __init__(self, tokenizer) -> None:
1079
+ super().__init__()
1080
+ self.tokenizer = tokenizer
1081
+ self.queue = response_queue
1082
+ self.query = query
1083
+ self.history = history
1084
+ self.response = ''
1085
+ self.cache = []
1086
+ self.received_inputs = False
1087
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1088
+
1089
+ def put(self, value):
1090
+ if len(value.shape) > 1 and value.shape[0] > 1:
1091
+ raise ValueError('ChatStreamer only supports batch size 1')
1092
+ elif len(value.shape) > 1:
1093
+ value = value[0]
1094
+
1095
+ if not self.received_inputs:
1096
+ # The first received value is input_ids, ignore here
1097
+ self.received_inputs = True
1098
+ return
1099
+
1100
+ self.cache.extend(value.tolist())
1101
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1102
+ if token.strip() != '<|im_end|>':
1103
+ self.response = self.response + token
1104
+ history = self.history + [(self.query, self.response)]
1105
+ self.queue.put((self.response, history))
1106
+ self.cache = []
1107
+ else:
1108
+ self.end()
1109
+
1110
+ def end(self):
1111
+ self.queue.put(None)
1112
+
1113
+ def stream_producer():
1114
+ return self.chat(
1115
+ tokenizer=tokenizer,
1116
+ query=query,
1117
+ streamer=ChatStreamer(tokenizer=tokenizer),
1118
+ history=history,
1119
+ max_new_tokens=max_new_tokens,
1120
+ do_sample=do_sample,
1121
+ temperature=temperature,
1122
+ top_p=top_p,
1123
+ **kwargs,
1124
+ )
1125
+
1126
+ def consumer():
1127
+ producer = threading.Thread(target=stream_producer)
1128
+ producer.start()
1129
+ while True:
1130
+ res = response_queue.get()
1131
+ if res is None:
1132
+ return
1133
+ yield res
1134
+
1135
+ return consumer()
1136
+
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,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ class mmMambaMLP(nn.Module):
132
+ def __init__(self, config):
133
+ super().__init__()
134
+ self.config = config
135
+ self.hidden_size = config.hidden_size
136
+ self.intermediate_size = config.intermediate_size
137
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
138
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
139
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
140
+ self.act_fn = ACT2FN[config.hidden_act]
141
+
142
+ def forward(self, x):
143
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
144
+
145
+ return down_proj
146
+
147
+
148
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
149
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
150
+ """
151
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
152
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
153
+ """
154
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
155
+ if n_rep == 1:
156
+ return hidden_states
157
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
158
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
159
+
160
+ def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
161
+ """
162
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
163
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
164
+ """
165
+ batch, num_key_value_heads, head_dim = hidden_states.shape
166
+ if n_rep == 1:
167
+ return hidden_states
168
+ hidden_states = hidden_states[:, :, None, :].expand(batch, num_key_value_heads, n_rep, head_dim)
169
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, head_dim)
170
+
171
+ class MHA_LM(nn.Module):
172
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
173
+
174
+ def __init__(self, config: mmMambaEmbeddingConfig, layer_idx: int):
175
+ super().__init__()
176
+ self.config = config
177
+ self.layer_idx = layer_idx
178
+ self.hidden_size = config.hidden_size
179
+ self.num_heads = config.num_attention_heads
180
+ self.head_dim = self.hidden_size // self.num_heads
181
+ self.num_key_value_heads = config.num_key_value_heads
182
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
183
+ self.max_position_embeddings = config.max_position_embeddings
184
+ self.is_causal = True
185
+ self.rotary_emb_dim = self.head_dim
186
+ self.softmax_scale = None
187
+ self.causal = True
188
+
189
+ if (self.head_dim * self.num_heads) != self.hidden_size:
190
+ raise ValueError(
191
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
192
+ f" and `num_heads`: {self.num_heads})."
193
+ )
194
+
195
+ self.wqkv = nn.Linear(
196
+ self.hidden_size,
197
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
198
+ bias=False,
199
+ )
200
+
201
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
202
+ assert RotaryEmbedding is not None, "rotary requires flash_attn to be installed"
203
+ self.rotary_emb = RotaryEmbedding(
204
+ self.head_dim,
205
+ base=self.config.rope_theta,
206
+ interleaved=False,
207
+ device=self.wo.weight.device,
208
+ )
209
+
210
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
211
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
212
+
213
+ def _update_kv_cache(self, kv, inference_params):
214
+ """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)"""
215
+ assert self.layer_idx is not None, "Generation requires layer_idx in the constructor"
216
+ return _update_kv_cache(kv, inference_params, self.layer_idx)
217
+
218
+ def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params):
219
+ """
220
+ Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention.
221
+ q: (batch_size, seqlen_q, nheads, head_dim)
222
+ kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim)
223
+ """
224
+ assert inference_params is not None and inference_params.seqlen_offset > 0
225
+ if self.rotary_emb_dim > 0:
226
+ self.rotary_emb._update_cos_sin_cache(
227
+ inference_params.max_seqlen, device=q.device, dtype=q.dtype
228
+ )
229
+ rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached
230
+ else:
231
+ rotary_cos, rotary_sin = None, None
232
+ batch = q.shape[0]
233
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
234
+ kv_cache = kv_cache[:batch]
235
+ cache_seqlens = (
236
+ inference_params.lengths_per_sample[:batch]
237
+ if inference_params.lengths_per_sample is not None
238
+ else inference_params.seqlen_offset
239
+ )
240
+ assert flash_attn_with_kvcache is not None, "flash_attn must be installed"
241
+ context = flash_attn_with_kvcache(
242
+ q,
243
+ kv_cache[:, :, 0],
244
+ kv_cache[:, :, 1],
245
+ kv[:, :, 0],
246
+ kv[:, :, 1],
247
+ rotary_cos=rotary_cos,
248
+ rotary_sin=rotary_sin,
249
+ cache_seqlens=cache_seqlens,
250
+ softmax_scale=self.softmax_scale,
251
+ causal=self.causal,
252
+ rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False,
253
+ )
254
+ return context
255
+
256
+ def _update_kvcache_attention(self, q, kv, inference_params):
257
+ """Write kv to inference_params, then do attention"""
258
+ if (
259
+ inference_params.seqlen_offset == 0
260
+ or flash_attn_with_kvcache is None
261
+ ):
262
+ # TODO: this only uses seqlen_offset and not lengths_per_sample.
263
+ kv = self._update_kv_cache(kv, inference_params)
264
+ k, v = kv.unbind(dim=-3)
265
+ #k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
266
+ #v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
267
+ attn_output = flash_attn_func(
268
+ q, k, v, 0.0, softmax_scale=None, causal=self.causal
269
+ )
270
+ return attn_output
271
+ else:
272
+ batch = q.shape[0]
273
+ kv_cache, _ = inference_params.key_value_memory_dict[self.layer_idx]
274
+ kv_cache = kv_cache[:batch]
275
+ cache_seqlens = (
276
+ inference_params.lengths_per_sample[:batch]
277
+ if inference_params.lengths_per_sample is not None
278
+ else inference_params.seqlen_offset
279
+ )
280
+ return flash_attn_with_kvcache(
281
+ q,
282
+ kv_cache[:, :, 0],
283
+ kv_cache[:, :, 1],
284
+ kv[:, :, 0],
285
+ kv[:, :, 1],
286
+ cache_seqlens=cache_seqlens,
287
+ softmax_scale=self.softmax_scale,
288
+ causal=self.causal,
289
+ )
290
+
291
+ def forward(
292
+ self,
293
+ hidden_states: torch.Tensor,
294
+ inference_params = None,
295
+ output_attentions: bool = False,
296
+ cache_position: Optional[torch.LongTensor] = None,#------------------------------------------------------------------------
297
+ use_cache: bool = False,
298
+ **kwargs,
299
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
300
+ if inference_params is not None and self.layer_idx not in inference_params.key_value_memory_dict:
301
+ inference_params.key_value_memory_dict[self.layer_idx] = self.allocate_inference_cache(
302
+ hidden_states.shape[0], inference_params.max_seqlen, dtype=hidden_states.dtype
303
+ )
304
+ seqlen_offset = (
305
+ 0
306
+ if inference_params is None
307
+ else (
308
+ inference_params.lengths_per_sample
309
+ if inference_params.lengths_per_sample is not None
310
+ else inference_params.seqlen_offset
311
+ )
312
+ )
313
+
314
+ bsz, q_len, _ = hidden_states.size()
315
+ rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None
316
+
317
+ qkv = self.wqkv(hidden_states)
318
+ qkv = rearrange(
319
+ qkv,
320
+ "b q (h gs d) -> b q h gs d",
321
+ gs=2 + self.num_key_value_groups,
322
+ d=self.head_dim,
323
+ )
324
+
325
+ q = qkv[..., : self.num_key_value_groups, :]
326
+ q = rearrange(q, "b q h gs d -> b q (h gs) d")
327
+ kv = qkv[..., self.num_key_value_groups:, :].transpose(2,3)
328
+ #kv = rearrange(kv, "b q h gs d -> b q (h gs) d")
329
+ #kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim)
330
+
331
+ if (
332
+ inference_params is None
333
+ or inference_params.seqlen_offset == 0
334
+ or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0)
335
+ ):
336
+ if self.rotary_emb_dim > 0:
337
+ q, kv = self.rotary_emb(
338
+ q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen
339
+ )
340
+ if inference_params is None:
341
+ k, v = kv.unbind(dim=-3)
342
+ k = torch.repeat_interleave(k, dim=2, repeats=self.num_heads // self.num_key_value_heads)
343
+ v = torch.repeat_interleave(v, dim=2, repeats=self.num_heads // self.num_key_value_heads)
344
+ context = F.scaled_dot_product_attention(
345
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, scale=None
346
+ ).transpose(1, 2)
347
+ else:
348
+ context = self._update_kvcache_attention(q, kv, inference_params)
349
+ else:
350
+ context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params)
351
+ context = rearrange(context, "... h d -> ... (h d)")
352
+ out = self.wo(context)
353
+ return out
354
+
355
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None):
356
+ dtype = self.wo.weight.dtype if dtype is None else dtype
357
+ device = self.wo.weight.device
358
+ kv_cache = torch.empty(
359
+ batch_size, max_seqlen, 2, self.num_key_value_heads, self.head_dim, dtype=dtype, device=device,
360
+ )
361
+ return kv_cache, None
362
+
363
+ class Mamba2_LM(nn.Module):
364
+ """
365
+ LoLCATs attention implementation initialized from a
366
+ `LlamaAttention` or `MistralAttention` object (base_attn)
367
+
368
+ Most of the arguments are directly tied to argparse args
369
+ - For now we don't support padding.
370
+ """
371
+ def __init__(self, config: mmMambaConfig, layer_idx: Optional[int] = None,
372
+ elementwise_affine: Optional[bool] = True,
373
+ norm_eps: float = 1e-5,
374
+ ):
375
+ super().__init__()
376
+ self.config = config
377
+ self.hidden_size = config.hidden_size
378
+ self.num_heads = config.num_attention_heads
379
+ self.head_dim = self.hidden_size // self.num_heads
380
+ self.num_key_value_heads = config.num_key_value_heads
381
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
382
+ self.max_position_embeddings = config.max_position_embeddings
383
+ self.layer_idx = layer_idx
384
+ self.bias = False
385
+ self.chunk_size = 128
386
+ conv_bias = True
387
+ self.conv_bias = conv_bias
388
+ self.d_conv = 2
389
+ self.activation="silu"
390
+ self.max_position_embeddings = config.max_position_embeddings
391
+ self.rope_theta = config.rope_theta
392
+
393
+ self.wvkqgdt = nn.Linear(
394
+ self.hidden_size,
395
+ (self.num_heads + 2 * self.num_key_value_heads + self.num_heads) * self.head_dim + self.num_heads,
396
+ bias=self.bias
397
+ )
398
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
399
+
400
+ self.device = self.wvkqgdt.weight.device
401
+ self.dtype = self.wvkqgdt.weight.dtype
402
+
403
+ conv_dim = self.num_heads * self.head_dim + 2 * self.num_key_value_heads * self.head_dim
404
+
405
+ self.conv1d = nn.Conv1d(
406
+ in_channels=conv_dim,
407
+ out_channels=conv_dim,
408
+ bias=self.conv_bias,
409
+ kernel_size=self.d_conv,
410
+ groups=conv_dim,
411
+ padding=self.d_conv - 1,
412
+ device=self.device,
413
+ dtype=self.dtype
414
+ )
415
+ with torch.no_grad():
416
+ self.conv1d.weight.zero_()
417
+ self.conv1d.weight[:, 0, 1] = 1
418
+ self.conv1d.bias.zero_()
419
+
420
+ # Activation after conv
421
+ if self.activation == "identity":
422
+ self.act = nn.Identity()
423
+ elif self.activation in ["silu", "swish"]:
424
+ self.act = nn.SiLU()
425
+ else:
426
+ raise ValueError(f"Unknown activation {self.activation}")
427
+
428
+ self.g_norm_swish_gate = FusedRMSNormSwishGate(hidden_size=self.head_dim, elementwise_affine=elementwise_affine, eps=norm_eps).to(self.dtype).to(self.device)
429
+
430
+ dt = torch.exp(
431
+ torch.rand(self.num_heads, dtype=self.dtype, device=self.device) * (math.log(0.1) - math.log(0.001))
432
+ + math.log(0.001)
433
+ )
434
+ dt = torch.clamp(dt, min=0.001)
435
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
436
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
437
+ self.dt_bias = nn.Parameter(inv_dt)
438
+ self.dt_bias._no_weight_decay = True
439
+
440
+ A_log_bias = torch.zeros(self.num_heads, dtype=self.dtype, device=self.device)
441
+ self.A_log_bias = nn.Parameter(A_log_bias)
442
+ self.A_log_bias._no_weight_decay = True
443
+
444
+ def forward(self,
445
+ hidden_states: torch.Tensor,
446
+ inference_params = None,
447
+ output_attentions: bool = False,
448
+ use_cache: bool = True,
449
+ **kwargs,
450
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
451
+ hidden_states = hidden_states.to(self.dtype)
452
+ vkqgdt = self.wvkqgdt(hidden_states)
453
+ vkq, g, dt = torch.split(
454
+ vkqgdt,
455
+ [
456
+ (2*self.num_key_value_heads+self.num_heads) * self.head_dim,
457
+ self.num_heads * self.head_dim,
458
+ self.num_heads,
459
+ ],
460
+ dim=2,
461
+ )
462
+ batch, seqlen, _ = hidden_states.shape
463
+ conv_state, ssm_state = None, None
464
+ if inference_params is not None:
465
+ conv_state, ssm_state = self._get_states_from_cache(inference_params, batch)
466
+
467
+ if use_cache and inference_params.seqlen_offset==0:
468
+ vkq, new_conv_states = causal_conv1d_fn(
469
+ vkq.transpose(1, 2),
470
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
471
+ self.conv1d.bias,
472
+ initial_states=None,
473
+ return_final_states=True,
474
+ activation=None if self.activation == "identity" else self.activation,
475
+ )
476
+
477
+ v, k, q = torch.split(
478
+ vkq,
479
+ [
480
+ self.num_key_value_heads * self.head_dim,
481
+ self.num_key_value_heads * self.head_dim,
482
+ self.num_heads * self.head_dim,
483
+ ],
484
+ dim=1,
485
+ )
486
+
487
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
488
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
489
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
490
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
491
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
492
+
493
+ A = -torch.exp(self.A_log_bias.float())
494
+
495
+ y, new_ssm_states = mamba_chunk_scan_combined(
496
+ x = v,
497
+ #x = v / F.softplus(A_log).to(v.dtype).unsqueeze(-1),
498
+ dt=dt,
499
+ dt_softplus=True,
500
+ A=A,
501
+ B=k,
502
+ C=q,
503
+ chunk_size=self.chunk_size,
504
+ dt_bias=self.dt_bias,
505
+ initial_states=None, # currently not supported by mamba_ssm.utils.generation
506
+ return_final_states=True,
507
+ )
508
+
509
+ conv_state.copy_(new_conv_states)
510
+ ssm_state.copy_(new_ssm_states)
511
+
512
+ elif use_cache and inference_params.seqlen_offset>0:
513
+
514
+ vkq = causal_conv1d_update(
515
+ vkq.transpose(1, 2).squeeze(-1),
516
+ conv_state,
517
+ self.conv1d.weight.squeeze(1),
518
+ self.conv1d.bias,
519
+ self.activation,
520
+ )
521
+
522
+ v, k, q = torch.split(
523
+ vkq,
524
+ [
525
+ self.num_key_value_heads * self.head_dim,
526
+ self.num_key_value_heads * self.head_dim,
527
+ self.num_heads * self.head_dim,
528
+ ],
529
+ dim=1,
530
+ )
531
+
532
+ v = rearrange(v, "b (h n) -> b h n", h=self.num_key_value_heads)
533
+ k = rearrange(k, "b (h n) -> b h n", h=self.num_key_value_heads)
534
+ q = rearrange(q, "b (h n) -> b h n", h=self.num_heads)
535
+ k = repeat_kv2(k, self.num_key_value_groups)
536
+ v = repeat_kv2(v, self.num_key_value_groups)
537
+
538
+ dt = dt.transpose(1, 2).squeeze(-1)
539
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
540
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
541
+ A = -torch.exp(self.A_log_bias.float())
542
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.head_dim).to(dtype=torch.float32)
543
+ D = torch.zeros((self.num_heads, self.head_dim), dtype=A.dtype, device=A.device)
544
+
545
+ y = selective_state_update(
546
+ ssm_state,
547
+ v,
548
+ dt,
549
+ A=A,
550
+ B=k,
551
+ C=q,
552
+ D=D,
553
+ dt_bias=dt_bias,
554
+ dt_softplus=True,
555
+ )
556
+
557
+ else:
558
+ vkq = causal_conv1d_fn(
559
+ vkq.transpose(1, 2),
560
+ rearrange(self.conv1d.weight, "d 1 w -> d w"),
561
+ self.conv1d.bias,
562
+ initial_states=None,
563
+ return_final_states=False,
564
+ activation=None if self.activation == "identity" else self.activation,
565
+ )
566
+
567
+ v, k, q = torch.split(
568
+ vkq,
569
+ [
570
+ self.num_key_value_heads * self.head_dim,
571
+ self.num_key_value_heads * self.head_dim,
572
+ self.num_heads * self.head_dim,
573
+ ],
574
+ dim=1,
575
+ )
576
+
577
+ v = rearrange(v, "b (h n) l -> b h l n", h=self.num_key_value_heads)
578
+ k = rearrange(k, "b (h n) l -> b h l n", h=self.num_key_value_heads)
579
+ q = rearrange(q, "b (h n) l -> b l h n", h=self.num_heads)
580
+ k = repeat_kv(k, self.num_key_value_groups).transpose(1, 2)
581
+ v = repeat_kv(v, self.num_key_value_groups).transpose(1, 2)
582
+
583
+ A = -torch.exp(self.A_log_bias.float())
584
+
585
+ y = mamba_chunk_scan_combined(
586
+ x = v,
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=False,
596
+ )
597
+
598
+ g = rearrange(g, 'b l (h d) -> b l h d', h=self.num_heads)
599
+ y_true = self.g_norm_swish_gate(y, g)
600
+ y_true = y_true.view(batch, seqlen, self.hidden_size)
601
+ y_true = self.o_proj(y_true)
602
+
603
+ return y_true
604
+
605
+ def _get_states_from_cache(self, inference_params, batch_size, initialize_states=False):
606
+ device = self.conv1d.weight.device
607
+ dtype = self.conv1d.weight.dtype
608
+ assert self.layer_idx is not None
609
+ if self.layer_idx not in inference_params.key_value_memory_dict:
610
+ batch_shape = (batch_size,)
611
+ conv_state = torch.zeros(
612
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
613
+ )
614
+ ssm_state = torch.zeros(
615
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
616
+ )
617
+ inference_params.key_value_memory_dict[self.layer_idx] = (conv_state, ssm_state)
618
+ else:
619
+ conv_state, ssm_state = inference_params.key_value_memory_dict[self.layer_idx]
620
+ # TODO: What if batch size changes between generation, and we reuse the same states?
621
+ if initialize_states:
622
+ conv_state.zero_()
623
+ ssm_state.zero_()
624
+ return conv_state, ssm_state
625
+
626
+
627
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
628
+ device = self.conv1d.weight.device
629
+ dtype = self.conv1d.weight.dtype
630
+ conv_state = torch.zeros(
631
+ batch_size, 2*self.hidden_size, self.d_conv-1, device=device, dtype=dtype
632
+ )
633
+
634
+ ssm_state = torch.zeros(
635
+ batch_size, self.num_heads, self.head_dim, self.head_dim, device=device, dtype=dtype
636
+ )
637
+ return conv_state, ssm_state
638
+
639
+
640
+ mmMamba_ATTENTION_CLASSES = {
641
+ 'mha': MHA_LM,
642
+ "mamba2":Mamba2_LM
643
+ }
644
+
645
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
646
+ class mmMambaDecoderLayer(nn.Module):
647
+ def __init__(self, config: mmMambaEmbeddingConfig, layer_idx: int, drop_path_rate=0.0):
648
+ super().__init__()
649
+ self.hidden_size = config.hidden_size
650
+ self.config = config
651
+ self.layer_idx = layer_idx
652
+
653
+ self.attention = mmMamba_ATTENTION_CLASSES[config.layers_block_type[layer_idx]](config=config, layer_idx=layer_idx)
654
+
655
+ self.feed_forward = mmMambaMLP(config)
656
+ self.attention_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
657
+ self.ffn_norm = mmMambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
658
+
659
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
660
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
661
+
662
+ def forward(
663
+ self,
664
+ hidden_states: torch.Tensor,
665
+ inference_params = None,
666
+ output_attentions: Optional[bool] = False,
667
+ use_cache: Optional[bool] = True,
668
+ **kwargs,
669
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
670
+ """
671
+ Args:
672
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
673
+ output_attentions (`bool`, *optional*):
674
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
675
+ returned tensors for more detail.
676
+ use_cache (`bool`, *optional*)
677
+ """
678
+ residual = hidden_states
679
+
680
+ hidden_states = self.attention_norm(hidden_states)
681
+
682
+ # Self Attention
683
+ hidden_states = self.attention(
684
+ hidden_states=hidden_states,
685
+ inference_params=inference_params,
686
+ output_attentions=output_attentions,
687
+ use_cache=use_cache,
688
+ **kwargs,
689
+ )
690
+ hidden_states = residual + self.drop_path1(hidden_states)
691
+
692
+ # Fully Connected
693
+ residual = hidden_states
694
+ hidden_states = self.ffn_norm(hidden_states)
695
+ hidden_states = self.feed_forward(hidden_states)
696
+
697
+ hidden_states = residual + self.drop_path2(hidden_states)
698
+
699
+ outputs = (hidden_states,)
700
+
701
+ if output_attentions:
702
+ outputs += (self_attn_weights,)
703
+
704
+ return outputs
705
+
706
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
707
+ return self.attention.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
708
+
709
+
710
+ class VisionEmbeddings(nn.Module):
711
+ def __init__(self, config: mmMambaEmbeddingConfig):
712
+ super().__init__()
713
+ self.config = config
714
+ self.embed_dim = config.hidden_size
715
+ self.image_size = config.image_size
716
+ self.patch_size = config.patch_size
717
+
718
+ self.class_embedding = nn.Parameter(
719
+ torch.randn(1, 1, self.embed_dim),
720
+ )
721
+
722
+ self.patch_embedding = nn.Conv2d(
723
+ in_channels=self.config.num_channels, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
724
+ )
725
+
726
+ self.num_patches = (self.image_size // self.patch_size) ** 2
727
+ self.num_positions = self.num_patches + 1
728
+
729
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
730
+
731
+ self.post_init()
732
+
733
+ def post_init(self):
734
+ for m in self.modules():
735
+ if isinstance(m, nn.Conv2d):
736
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
737
+ if m.bias is not None:
738
+ nn.init.zeros_(m.bias)
739
+ if isinstance(m, nn.Linear):
740
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
741
+ if m.bias is not None:
742
+ nn.init.zeros_(m.bias)
743
+
744
+ def _get_pos_embed(self, pos_embed, H, W):
745
+ target_dtype = pos_embed.dtype
746
+ pos_embed = pos_embed.float().reshape(
747
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
748
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False).\
749
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
750
+ return pos_embed
751
+
752
+ def forward(self, pixel_values: torch.FloatTensor,
753
+ use_cls_token=False,
754
+ ) -> torch.Tensor:
755
+ target_dtype = self.patch_embedding.weight.dtype
756
+ pixel_values = pixel_values.to(target_dtype)
757
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
758
+ batch_size, _, height, width = patch_embeds.shape
759
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
760
+ if use_cls_token:
761
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
762
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
763
+ assert not self.config.use_2d_sincos_pos_embed, '2D SinCos pos embed is not supported with use_cls_token'
764
+ position_embedding = torch.cat([
765
+ self.position_embedding[:, :1, :],
766
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
767
+ ], dim=1)
768
+ embeddings = embeddings + position_embedding
769
+ else:
770
+ position_embedding = self._get_pos_embed(self.position_embedding[:, 1:, :], height, width).to(target_dtype)
771
+ embeddings = patch_embeds + position_embedding
772
+
773
+ return embeddings
774
+
775
+
776
+ class mmMambaEmbedding(PreTrainedModel):
777
+ config_class = mmMambaEmbeddingConfig
778
+ _supports_flash_attn_2 = True
779
+
780
+ def __init__(self, config: mmMambaEmbeddingConfig):
781
+ super().__init__(config)
782
+ self.config = config
783
+ self.hidden_size = self.config.hidden_size
784
+ self.gradient_checkpointing = True
785
+
786
+ self.vision_embeddings = VisionEmbeddings(config)
787
+ self.llm_text_embeddings = nn.Embedding(self.config.llm_vocab_size, self.config.llm_hidden_size)
788
+ self.special_token_maps = config.special_token_maps
789
+ if len(self.special_token_maps) > 0:
790
+ self.special_text_embeddings = nn.Embedding(len(config.special_token_maps), self.config.llm_hidden_size)
791
+
792
+ assert self.config.use_ls is False, 'LS is not supported in mmMamba'
793
+ if hasattr(config, 'drop_path_rate'):
794
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
795
+ else:
796
+ dpr = [0.0] * config.num_hidden_layers
797
+ self.encoder = nn.ModuleList([
798
+ mmMambaDecoderLayer(config, idx, dpr[idx]) for idx in range(config.num_hidden_layers)
799
+ ])
800
+
801
+ if self.config.use_pixel_shuffle_proj:
802
+ self.pixel_shuffle_proj = nn.Sequential(
803
+ nn.Linear(int(config.hidden_size / (config.downsample_ratio * config.downsample_ratio)), config.hidden_size),
804
+ nn.GELU(),
805
+ nn.Linear(config.hidden_size, config.hidden_size)
806
+ )
807
+
808
+ self.num_img_tokens = (self.config.image_size // self.config.patch_size) ** 2
809
+
810
+ def set_gradient_checkpointing(self):
811
+ self.gradient_checkpointing = True
812
+ for layer in self.encoder:
813
+ layer.gradient_checkpointing = True
814
+
815
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
816
+ pos_emb = self.vision_embeddings.position_embedding
817
+ _, num_positions, embed_dim = pos_emb.shape
818
+ cls_emb = pos_emb[:, :1, :]
819
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
820
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
821
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
822
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
823
+ self.vision_embeddings.position_embedding = nn.Parameter(pos_emb)
824
+ self.vision_embeddings.image_size = new_size
825
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
826
+
827
+ def replace_img_tokens(self, input_ids, hidden_states, vision_hidden_states):
828
+ img_context_token_mask = (input_ids == self.config.img_context_token_id)
829
+ hidden_states[img_context_token_mask] = hidden_states[img_context_token_mask] * 0.0 + vision_hidden_states.flatten(0, 1)
830
+
831
+ return hidden_states
832
+
833
+ def get_ignore_mask(self, input_ids):
834
+ ignore_ids = torch.tensor(
835
+ [self.special_token_maps[token] for token in [IMG_START_TOKEN, IMG_END_TOKEN]],
836
+ device=input_ids.device)
837
+ ignore_mask = torch.isin(input_ids, ignore_ids)
838
+
839
+ return ignore_mask
840
+
841
+ def get_text_mask(self, input_ids):
842
+ txt_mask = (input_ids != self.config.img_context_token_id)
843
+
844
+ return txt_mask
845
+
846
+ def get_input_embeddings(self, input_ids):
847
+ special_mask = input_ids > self.llm_text_embeddings.weight.shape[0] - 1
848
+ llm_embeddings = self.llm_text_embeddings(input_ids * (~special_mask).to(input_ids))
849
+
850
+ if len(self.special_token_maps) > 0:
851
+ special_embeddings = self.special_text_embeddings((input_ids - self.llm_text_embeddings.weight.shape[0]) * special_mask.to(input_ids))
852
+ special_mask = special_mask.unsqueeze(-1)
853
+ text_embeddings = llm_embeddings * (~special_mask).to(llm_embeddings) + \
854
+ special_embeddings * special_mask.to(llm_embeddings)
855
+ else:
856
+ text_embeddings = llm_embeddings
857
+
858
+ return text_embeddings
859
+
860
+ def get_txt_embeddings(self, input_ids):
861
+ B, L = input_ids.shape
862
+ txt_mask = (input_ids != self.config.img_context_token_id)
863
+ txt_embeddings = self.llm_text_embeddings(input_ids[txt_mask])
864
+ txt_embeddings = txt_embeddings.reshape(-1, txt_embeddings.shape[-1])
865
+
866
+ return txt_embeddings
867
+
868
+ def get_txt_feature(self, input_ids, feature):
869
+ B, L, C = feature.shape
870
+ txt_mask = (input_ids != self.config.img_context_token_id)
871
+ txt_feature = feature[txt_mask].reshape(-1, C)
872
+
873
+ return txt_feature
874
+
875
+ def get_img_feature(self, input_ids, feature):
876
+ B, L, C = feature.shape
877
+ img_mask = (input_ids == self.config.img_context_token_id)
878
+ img_feature = feature[img_mask].reshape(-1, C)
879
+
880
+ return img_feature
881
+
882
+ def pixel_shuffle(self, x, scale_factor=0.5):
883
+ if getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'post':
884
+ x = x.view(x.shape[0]//self.num_img_tokens, self.num_img_tokens, -1)
885
+
886
+ n, l, c = x.size()
887
+ h = w = int(l ** 0.5)
888
+ # N, W, H, C --> N, W, H * scale, C // scale
889
+ x = x.reshape(n, w, int(h * scale_factor), int(c / scale_factor))
890
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
891
+ x = x.permute(0, 2, 1, 3).contiguous()
892
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
893
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
894
+ int(c / (scale_factor * scale_factor)))
895
+ x = x.permute(0, 2, 1, 3).reshape(n, int(l * scale_factor * scale_factor), int(c / (scale_factor * scale_factor))).contiguous()
896
+
897
+ if getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'post':
898
+ x = x.view(int(x.shape[0]*self.num_img_tokens*(self.config.downsample_ratio**2)), -1)
899
+ return x
900
+
901
+ def forward(
902
+ self,
903
+ input_ids: Optional[torch.LongTensor] = None,
904
+ pixel_values: Optional[torch.FloatTensor] = None,
905
+ inference_params = None,
906
+ output_hidden_states: Optional[bool] = None,
907
+ return_dict: Optional[bool] = None,
908
+ use_cache: Optional[bool] = True,
909
+ ):
910
+ output_hidden_states = (
911
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
912
+ )
913
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
914
+ if pixel_values is not None:
915
+ if len(pixel_values.shape) == 4:
916
+ if self.gradient_checkpointing and self.training:
917
+ vision_hidden_states = torch.utils.checkpoint.checkpoint(self.vision_embeddings, pixel_values)
918
+ else:
919
+ vision_hidden_states = self.vision_embeddings(pixel_values)
920
+
921
+ if self.config.use_pixel_shuffle_proj and getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'pre':
922
+ vision_hidden_states = self.pixel_shuffle(vision_hidden_states, scale_factor=self.config.downsample_ratio)
923
+ if self.gradient_checkpointing and self.training:
924
+ vision_hidden_states = torch.utils.checkpoint.checkpoint(self.pixel_shuffle_proj, vision_hidden_states)
925
+ else:
926
+ vision_hidden_states = self.pixel_shuffle_proj(vision_hidden_states)
927
+
928
+ hidden_states = self.get_input_embeddings(input_ids)
929
+ hidden_states = self.replace_img_tokens(input_ids, hidden_states, vision_hidden_states)
930
+ else:
931
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
932
+ else:
933
+ hidden_states = self.get_input_embeddings(input_ids)
934
+
935
+ for layer_idx, layer_module in enumerate(self.encoder):
936
+ if self.gradient_checkpointing and self.training:
937
+ assert use_cache is None, 'Gradient checkpointing is not compatible with cache'
938
+ outputs = torch.utils.checkpoint.checkpoint(layer_module,
939
+ hidden_states,
940
+ inference_params,
941
+ None, False, False,
942
+ )
943
+ hidden_states = outputs[0]
944
+ else:
945
+ outputs = layer_module(
946
+ hidden_states=hidden_states,
947
+ inference_params=inference_params,
948
+ use_cache=use_cache,
949
+ )
950
+ hidden_states = outputs[0]
951
+
952
+
953
+ img_feature = self.get_img_feature(input_ids, hidden_states)
954
+
955
+ if self.config.use_pixel_shuffle_proj and getattr(self.config, 'pixel_shuffle_loc', 'pre') == 'post':
956
+ img_feature = self.pixel_shuffle(img_feature, scale_factor=self.config.downsample_ratio)
957
+ img_feature = self.pixel_shuffle_proj(img_feature)
958
+
959
+ return img_feature, hidden_states
960
+
961
+ def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
962
+ return {
963
+ layer.layer_idx: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
964
+ for layer in self.encoder
965
+ }
966
+
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
+ }