1 commited on
Commit
75f07f8
·
1 Parent(s): c4424af
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 1024,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
README.md CHANGED
The diff for this file is too large to render. See raw diff
 
added_tokens.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|execute_end|>": 73444,
3
+ "<|execute_start|>": 73443,
4
+ "<|fim_middle|>": 73446,
5
+ "<|fim_prefix|>": 73445,
6
+ "<|fim_suffix|>": 73447,
7
+ "<|im_end|>": 73440,
8
+ "<|im_start|>": 73441,
9
+ "<|tool_call|>": 73442
10
+ }
config.json ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openbmb/UltraRAG-Embedding",
3
+ "adapt_mean_pooling": true,
4
+ "architectures": [
5
+ "MiniCPMModel"
6
+ ],
7
+ "attention_bias": false,
8
+ "attention_dropout": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_minicpm.MiniCPMConfig",
11
+ "AutoModel": "modeling_minicpm.MiniCPMModel",
12
+ "AutoModelForCausalLM": "modeling_minicpm.MiniCPMForCausalLM",
13
+ "AutoModelForSeq2SeqLM": "modeling_minicpm.MiniCPMForCausalLM",
14
+ "AutoModelForSequenceClassification": "modeling_minicpm.MiniCPMForSequenceClassification"
15
+ },
16
+ "bos_token_id": 1,
17
+ "dim_model_base": 256,
18
+ "eos_token_id": 2,
19
+ "hidden_act": "silu",
20
+ "hidden_size": 1024,
21
+ "initializer_range": 0.1,
22
+ "intermediate_size": 4096,
23
+ "is_causal": false,
24
+ "max_position_embeddings": 4096,
25
+ "model_type": "minicpm",
26
+ "num_attention_heads": 16,
27
+ "num_hidden_layers": 24,
28
+ "num_key_value_heads": 2,
29
+ "pretraining_tp": 1,
30
+ "rms_norm_eps": 1e-05,
31
+ "rope_scaling": {
32
+ "long_factor": [
33
+ 1.0004360675811768,
34
+ 1.0668443441390991,
35
+ 1.1631425619125366,
36
+ 1.3025742769241333,
37
+ 1.5040205717086792,
38
+ 1.7941505908966064,
39
+ 2.2101221084594727,
40
+ 2.802666664123535,
41
+ 3.6389970779418945,
42
+ 4.804192543029785,
43
+ 6.39855432510376,
44
+ 8.527148246765137,
45
+ 11.277542114257812,
46
+ 14.684998512268066,
47
+ 18.69317054748535,
48
+ 23.13019371032715,
49
+ 27.72362518310547,
50
+ 32.1606559753418,
51
+ 36.168827056884766,
52
+ 39.57627868652344,
53
+ 42.32667541503906,
54
+ 44.45526885986328,
55
+ 46.04962921142578,
56
+ 47.21482849121094,
57
+ 48.05115509033203,
58
+ 48.64370346069336,
59
+ 49.05967712402344,
60
+ 49.34980392456055,
61
+ 49.551246643066406,
62
+ 49.69068145751953,
63
+ 49.78697967529297,
64
+ 49.85338592529297
65
+ ],
66
+ "original_max_position_embeddings": 4096,
67
+ "short_factor": [
68
+ 1.0004360675811768,
69
+ 1.0668443441390991,
70
+ 1.1631425619125366,
71
+ 1.3025742769241333,
72
+ 1.5040205717086792,
73
+ 1.7941505908966064,
74
+ 2.2101221084594727,
75
+ 2.802666664123535,
76
+ 3.6389970779418945,
77
+ 4.804192543029785,
78
+ 6.39855432510376,
79
+ 8.527148246765137,
80
+ 11.277542114257812,
81
+ 14.684998512268066,
82
+ 18.69317054748535,
83
+ 23.13019371032715,
84
+ 27.72362518310547,
85
+ 32.1606559753418,
86
+ 36.168827056884766,
87
+ 39.57627868652344,
88
+ 42.32667541503906,
89
+ 44.45526885986328,
90
+ 46.04962921142578,
91
+ 47.21482849121094,
92
+ 48.05115509033203,
93
+ 48.64370346069336,
94
+ 49.05967712402344,
95
+ 49.34980392456055,
96
+ 49.551246643066406,
97
+ 49.69068145751953,
98
+ 49.78697967529297,
99
+ 49.85338592529297
100
+ ],
101
+ "type": "longrope"
102
+ },
103
+ "rope_theta": 10000.0,
104
+ "scale_depth": 1.4,
105
+ "scale_emb": 12,
106
+ "torch_dtype": "bfloat16",
107
+ "transformers_version": "4.37.2",
108
+ "use_cache": false,
109
+ "vocab_size": 73448
110
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "2.7.0",
4
+ "transformers": "4.37.2",
5
+ "pytorch": "2.0.1+cu121"
6
+ },
7
+ "prompts": {},
8
+ "default_prompt_name": null
9
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ MiniCPM model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ MINICPM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class MiniCPMConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`MiniCPMModel`]. It is used to instantiate an MiniCPM
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the MiniCPM-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the MiniCPM model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`MiniCPMModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
64
+ The maximum sequence length that this model might ever be used with. MiniCPM 1 supports up to 2048 tokens,
65
+ MiniCPM 2 up to 4096, CodeMiniCPM up to 16384.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ Padding token id.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ Beginning of stream token id.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ End of stream token id.
79
+ pretraining_tp (`int`, *optional*, defaults to 1):
80
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
81
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
82
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
83
+ issue](https://github.com/pytorch/pytorch/issues/76232).
84
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
85
+ Whether to tie weight embeddings
86
+ rope_theta (`float`, *optional*, defaults to 10000.0):
87
+ The base period of the RoPE embeddings.
88
+ rope_scaling (`Dict`, *optional*):
89
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
90
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
91
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
92
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
93
+ these scaling strategies behave:
94
+ https://www.reddit.com/r/LocalMiniCPM/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
95
+ experimental feature, subject to breaking API changes in future versions.
96
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
97
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
98
+ attention_dropout (`float`, *optional*, defaults to 0.0):
99
+ The dropout ratio for the attention probabilities.
100
+
101
+ ```python
102
+ >>> from transformers import MiniCPMModel, MiniCPMConfig
103
+
104
+ >>> # Initializing a MiniCPM minicpm-7b style configuration
105
+ >>> configuration = MiniCPMConfig()
106
+
107
+ >>> # Initializing a model from the minicpm-7b style configuration
108
+ >>> model = MiniCPMModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "minicpm"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32000,
120
+ hidden_size=4096,
121
+ intermediate_size=11008,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ hidden_act="silu",
126
+ max_position_embeddings=2048,
127
+ initializer_range=0.02,
128
+ rms_norm_eps=1e-6,
129
+ use_cache=True,
130
+ pad_token_id=None,
131
+ bos_token_id=1,
132
+ eos_token_id=2,
133
+ pretraining_tp=1,
134
+ tie_word_embeddings=True,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ attention_bias=False,
138
+ attention_dropout=0.0,
139
+ scale_emb=1,
140
+ dim_model_base=1,
141
+ scale_depth=1,
142
+ is_causal=True,
143
+ adapt_mean_pooling=True,
144
+ **kwargs,
145
+ ):
146
+ self.vocab_size = vocab_size
147
+ self.max_position_embeddings = max_position_embeddings
148
+ self.hidden_size = hidden_size
149
+ self.intermediate_size = intermediate_size
150
+ self.num_hidden_layers = num_hidden_layers
151
+ self.num_attention_heads = num_attention_heads
152
+
153
+ # for backward compatibility
154
+ if num_key_value_heads is None:
155
+ num_key_value_heads = num_attention_heads
156
+
157
+ self.num_key_value_heads = num_key_value_heads
158
+ self.hidden_act = hidden_act
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.pretraining_tp = pretraining_tp
162
+ self.use_cache = use_cache
163
+ self.rope_theta = rope_theta
164
+ self.rope_scaling = rope_scaling
165
+ # self._rope_scaling_validation()
166
+ self.attention_bias = attention_bias
167
+ self.attention_dropout = attention_dropout
168
+ self.scale_emb = scale_emb
169
+ self.dim_model_base = dim_model_base
170
+ self.scale_depth = scale_depth
171
+ self.is_causal = is_causal
172
+ self.adapt_mean_pooling = adapt_mean_pooling
173
+
174
+ super().__init__(
175
+ pad_token_id=pad_token_id,
176
+ bos_token_id=bos_token_id,
177
+ eos_token_id=eos_token_id,
178
+ tie_word_embeddings=tie_word_embeddings,
179
+ **kwargs,
180
+ )
181
+ # try:
182
+ # import flash_attn
183
+ # self._attn_implementation = "flash_attention_2"
184
+ # except:
185
+ # pass
186
+
187
+ def _rope_scaling_validation(self):
188
+ """
189
+ Validate the `rope_scaling` configuration.
190
+ """
191
+ if self.rope_scaling is None:
192
+ return
193
+
194
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
195
+ raise ValueError(
196
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
197
+ f"got {self.rope_scaling}"
198
+ )
199
+ rope_scaling_type = self.rope_scaling.get("type", None)
200
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
201
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
202
+ raise ValueError(
203
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
204
+ )
205
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
206
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:109f243eddb0ae63ec4bbcb16ddb127d65399184a4e01565a628911c9c4c6afc
3
+ size 867773472
modeling_minicpm.py ADDED
@@ -0,0 +1,1806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch MiniCPM model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union, Dict
24
+ import os
25
+ from tqdm import tqdm
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+ import numpy as np
32
+ from copy import deepcopy
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers import AutoTokenizer
37
+ from transformers.modeling_attn_mask_utils import (
38
+ AttentionMaskConverter,
39
+ _prepare_4d_attention_mask,
40
+ _prepare_4d_causal_attention_mask,
41
+ _prepare_4d_causal_attention_mask_for_sdpa,
42
+ _prepare_4d_attention_mask_for_sdpa,
43
+ )
44
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
45
+ from transformers.modeling_utils import PreTrainedModel
46
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
47
+ from transformers.utils import (
48
+ add_start_docstrings,
49
+ add_start_docstrings_to_model_forward,
50
+ is_flash_attn_2_available,
51
+ is_flash_attn_greater_or_equal_2_10,
52
+ logging,
53
+ replace_return_docstrings,
54
+ )
55
+ from transformers.utils.import_utils import is_torch_fx_available
56
+ from .configuration_minicpm import MiniCPMConfig
57
+ import re
58
+
59
+ try:
60
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
61
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
62
+ except:
63
+ pass
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ if not is_torch_greater_or_equal_than_1_13:
70
+ import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "MiniCPMConfig"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
85
+ return (
86
+ indices,
87
+ cu_seqlens,
88
+ max_seqlen_in_batch,
89
+ )
90
+
91
+
92
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
93
+ warnings.warn(
94
+ "Calling `transformers.models.minicpm.modeling_minicpm._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
95
+ )
96
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
97
+
98
+
99
+ def _make_causal_mask(
100
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
101
+ ):
102
+ warnings.warn(
103
+ "Calling `transformers.models.minicpm.modeling_minicpm._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.minicpm.modeling_minicpm.AttentionMaskConverter._make_causal_mask"
104
+ )
105
+ return AttentionMaskConverter._make_causal_mask(
106
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
107
+ )
108
+
109
+ # @torch.jit.script # type: ignore
110
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
111
+ old_dtype = hidden.dtype
112
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
113
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
114
+ return hidden * weight
115
+
116
+
117
+ class MiniCPMRMSNorm(nn.Module):
118
+ def __init__(self, hidden_size, eps=1e-6):
119
+ """
120
+ MiniCPMRMSNorm 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
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
128
+
129
+
130
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
131
+
132
+
133
+ class MiniCPMRotaryEmbedding(nn.Module):
134
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
135
+ super().__init__()
136
+
137
+ self.dim = dim
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.base = base
140
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
141
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
142
+
143
+ # Build here to make `torch.jit.trace` work.
144
+ self._set_cos_sin_cache(
145
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
146
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
147
+ )
148
+
149
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
150
+ self.max_seq_len_cached = seq_len
151
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
152
+ freqs = torch.outer(t, self.inv_freq)
153
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
154
+ emb = torch.cat((freqs, freqs), dim=-1)
155
+
156
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
157
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
158
+
159
+ def forward(self, x, seq_len=None):
160
+ # x: [bs, num_attention_heads, seq_len, head_size]
161
+ if seq_len > self.max_seq_len_cached:
162
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
163
+
164
+ return (
165
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
166
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
167
+ )
168
+
169
+
170
+ class MiniCPMLongRoPE(MiniCPMRotaryEmbedding):
171
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
172
+
173
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, short_factor=None, long_factor=None, original_max_position_embeddings=None):
174
+ self.short_factor = short_factor
175
+ self.long_factor = long_factor
176
+ self.original_max_position_embeddings = original_max_position_embeddings
177
+ scale = (max_position_embeddings /
178
+ self.original_max_position_embeddings)
179
+ self.scaling_factor = math.sqrt(
180
+ 1 + math.log(scale) /
181
+ math.log(self.original_max_position_embeddings))
182
+ super().__init__(dim, max_position_embeddings, base, device)
183
+
184
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
185
+ self.max_seq_len_cached = seq_len
186
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
187
+ if seq_len > self.original_max_position_embeddings:
188
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=device)
189
+ else:
190
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=device)
191
+
192
+ freqs = torch.mul(
193
+ torch.outer(t, 1.0 / ext_factors).to(device=device),
194
+ self.inv_freq.to(device=device).to(dtype)
195
+ )
196
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
197
+ emb = torch.cat((freqs, freqs), dim=-1)
198
+ self.register_buffer("cos_cached", emb.cos().to(dtype) * self.scaling_factor, persistent=False)
199
+ self.register_buffer("sin_cached", emb.sin().to(dtype) * self.scaling_factor, persistent=False)
200
+
201
+
202
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
203
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
204
+
205
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
206
+ self.scaling_factor = scaling_factor
207
+ super().__init__(dim, max_position_embeddings, base, device)
208
+
209
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
210
+ self.max_seq_len_cached = seq_len
211
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
212
+ t = t / self.scaling_factor
213
+
214
+ freqs = torch.outer(t, self.inv_freq)
215
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
216
+ emb = torch.cat((freqs, freqs), dim=-1)
217
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
218
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
219
+
220
+
221
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
222
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
223
+
224
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
225
+ self.scaling_factor = scaling_factor
226
+ super().__init__(dim, max_position_embeddings, base, device)
227
+
228
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
229
+ self.max_seq_len_cached = seq_len
230
+
231
+ if seq_len > self.max_position_embeddings:
232
+ base = self.base * (
233
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
234
+ ) ** (self.dim / (self.dim - 2))
235
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
236
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
237
+
238
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
239
+
240
+ freqs = torch.outer(t, self.inv_freq)
241
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
242
+ emb = torch.cat((freqs, freqs), dim=-1)
243
+
244
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
245
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
246
+
247
+
248
+ def rotate_half(x):
249
+ """Rotates half the hidden dims of the input."""
250
+ x1 = x[..., : x.shape[-1] // 2]
251
+ x2 = x[..., x.shape[-1] // 2 :]
252
+ return torch.cat((-x2, x1), dim=-1)
253
+
254
+
255
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
256
+ """Applies Rotary Position Embedding to the query and key tensors.
257
+
258
+ Args:
259
+ q (`torch.Tensor`): The query tensor.
260
+ k (`torch.Tensor`): The key tensor.
261
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
262
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
263
+ position_ids (`torch.Tensor`):
264
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
265
+ used to pass offsetted position ids when working with a KV-cache.
266
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
267
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
268
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
269
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
270
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
271
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
272
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
273
+ Returns:
274
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
275
+ """
276
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
277
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
278
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
279
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
280
+ orig_dtype = k.dtype
281
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
282
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
283
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
284
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
285
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
286
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
287
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
288
+
289
+ class MiniCPMMLP(nn.Module):
290
+ def __init__(self, config):
291
+ super().__init__()
292
+ self.config = config
293
+ self.hidden_size = config.hidden_size
294
+ self.intermediate_size = config.intermediate_size
295
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
296
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
297
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
298
+ self.act_fn = ACT2FN[config.hidden_act]
299
+
300
+ def forward(self, x):
301
+ if self.config.pretraining_tp > 1:
302
+ slice = self.intermediate_size // self.config.pretraining_tp
303
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
304
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
305
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
306
+
307
+ gate_proj = torch.cat(
308
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
309
+ )
310
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
311
+
312
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
313
+ down_proj = [
314
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
315
+ ]
316
+ down_proj = sum(down_proj)
317
+ else:
318
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
319
+
320
+ return down_proj
321
+
322
+
323
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
324
+ """
325
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
326
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
327
+ """
328
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
329
+ if n_rep == 1:
330
+ return hidden_states
331
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
332
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
333
+
334
+
335
+
336
+ class MiniCPMAttention(nn.Module):
337
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
338
+
339
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
340
+ super().__init__()
341
+ self.config = config
342
+ self.layer_idx = layer_idx
343
+ if layer_idx is None:
344
+ logger.warning_once(
345
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
346
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
347
+ "when creating this class."
348
+ )
349
+
350
+ self.attention_dropout = config.attention_dropout
351
+ self.hidden_size = config.hidden_size
352
+ self.num_heads = config.num_attention_heads
353
+ self.head_dim = self.hidden_size // self.num_heads
354
+ self.num_key_value_heads = config.num_key_value_heads
355
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
356
+ self.max_position_embeddings = config.max_position_embeddings
357
+ self.rope_theta = config.rope_theta
358
+
359
+ self.is_causal = config.is_causal
360
+
361
+ if (self.head_dim * self.num_heads) != self.hidden_size:
362
+ raise ValueError(
363
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
364
+ f" and `num_heads`: {self.num_heads})."
365
+ )
366
+
367
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
368
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
369
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
370
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
371
+ self._init_rope()
372
+
373
+ def _init_rope(self):
374
+ if self.config.rope_scaling is None:
375
+ self.rotary_emb = MiniCPMRotaryEmbedding(
376
+ self.head_dim,
377
+ max_position_embeddings=self.max_position_embeddings,
378
+ base=self.rope_theta,
379
+ )
380
+ else:
381
+ scaling_type = self.config.rope_scaling["type"]
382
+
383
+ if scaling_type == "linear":
384
+ scaling_factor = self.config.rope_scaling["factor"]
385
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
386
+ self.head_dim,
387
+ max_position_embeddings=self.max_position_embeddings,
388
+ scaling_factor=scaling_factor,
389
+ base=self.rope_theta,
390
+ )
391
+ elif scaling_type == "dynamic":
392
+ scaling_factor = self.config.rope_scaling["factor"]
393
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
394
+ self.head_dim,
395
+ max_position_embeddings=self.max_position_embeddings,
396
+ scaling_factor=scaling_factor,
397
+ base=self.rope_theta,
398
+ )
399
+ elif scaling_type == "longrope":
400
+ self.rotary_emb = MiniCPMLongRoPE(
401
+ self.head_dim,
402
+ max_position_embeddings=self.max_position_embeddings,
403
+ short_factor = self.config.rope_scaling["short_factor"],
404
+ long_factor = self.config.rope_scaling["long_factor"],
405
+ base=self.rope_theta,
406
+ original_max_position_embeddings=self.config.rope_scaling["original_max_position_embeddings"]
407
+ )
408
+ else:
409
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
410
+
411
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
412
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
413
+
414
+ def forward(
415
+ self,
416
+ hidden_states: torch.Tensor,
417
+ attention_mask: Optional[torch.Tensor] = None,
418
+ position_ids: Optional[torch.LongTensor] = None,
419
+ past_key_value: Optional[Cache] = None,
420
+ output_attentions: bool = False,
421
+ use_cache: bool = False,
422
+ **kwargs,
423
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
424
+ if "padding_mask" in kwargs:
425
+ warnings.warn(
426
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
427
+ )
428
+
429
+ bsz, q_len, _ = hidden_states.size()
430
+
431
+ if self.config.pretraining_tp > 1:
432
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
433
+ query_slices = self.q_proj.weight.split(
434
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
435
+ )
436
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
437
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
438
+
439
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
440
+ query_states = torch.cat(query_states, dim=-1)
441
+
442
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
443
+ key_states = torch.cat(key_states, dim=-1)
444
+
445
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
446
+ value_states = torch.cat(value_states, dim=-1)
447
+
448
+ else:
449
+ query_states = self.q_proj(hidden_states)
450
+ key_states = self.k_proj(hidden_states)
451
+ value_states = self.v_proj(hidden_states)
452
+
453
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
454
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
455
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
456
+
457
+ kv_seq_len = key_states.shape[-2]
458
+ if past_key_value is not None:
459
+ if self.layer_idx is None:
460
+ raise ValueError(
461
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
462
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
463
+ "with a layer index."
464
+ )
465
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
466
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
467
+
468
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
469
+
470
+ if past_key_value is not None:
471
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
472
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
473
+
474
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
475
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
476
+
477
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
478
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
479
+ raise ValueError(
480
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
481
+ f" {attn_weights.size()}"
482
+ )
483
+
484
+ if attention_mask is not None:
485
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
486
+ raise ValueError(
487
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
488
+ )
489
+ attn_weights = attn_weights + attention_mask
490
+
491
+ # upcast attention to fp32
492
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
493
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
494
+ attn_output = torch.matmul(attn_weights, value_states)
495
+
496
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
497
+ raise ValueError(
498
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
499
+ f" {attn_output.size()}"
500
+ )
501
+
502
+ attn_output = attn_output.transpose(1, 2).contiguous()
503
+
504
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
505
+
506
+ if self.config.pretraining_tp > 1:
507
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
508
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
509
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
510
+ else:
511
+ attn_output = self.o_proj(attn_output)
512
+
513
+ if not output_attentions:
514
+ attn_weights = None
515
+
516
+ return attn_output, attn_weights, past_key_value
517
+
518
+
519
+ class MiniCPMFlashAttention2(MiniCPMAttention):
520
+ """
521
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
522
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
523
+ flash attention and deal with padding tokens in case the input contains any of them.
524
+ """
525
+
526
+ def __init__(self, *args, **kwargs):
527
+ super().__init__(*args, **kwargs)
528
+
529
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
530
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
531
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
532
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
533
+
534
+ def forward(
535
+ self,
536
+ hidden_states: torch.Tensor,
537
+ attention_mask: Optional[torch.LongTensor] = None,
538
+ position_ids: Optional[torch.LongTensor] = None,
539
+ past_key_value: Optional[Cache] = None,
540
+ output_attentions: bool = False,
541
+ use_cache: bool = False,
542
+ **kwargs,
543
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
544
+ # MiniCPMFlashAttention2 attention does not support output_attentions
545
+ if "padding_mask" in kwargs:
546
+ warnings.warn(
547
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
548
+ )
549
+
550
+ # overwrite attention_mask with padding_mask
551
+ attention_mask = kwargs.pop("padding_mask")
552
+
553
+ output_attentions = False
554
+
555
+ bsz, q_len, _ = hidden_states.size()
556
+
557
+ query_states = self.q_proj(hidden_states)
558
+ key_states = self.k_proj(hidden_states)
559
+ value_states = self.v_proj(hidden_states)
560
+
561
+ # Flash attention requires the input to have the shape
562
+ # batch_size x seq_length x head_dim x hidden_dim
563
+ # therefore we just need to keep the original shape
564
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
565
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
566
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
567
+
568
+ kv_seq_len = key_states.shape[-2]
569
+ if past_key_value is not None:
570
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
571
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
572
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
573
+
574
+ if past_key_value is not None:
575
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
576
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
577
+
578
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
579
+ # to be able to avoid many of these transpose/reshape/view.
580
+ query_states = query_states.transpose(1, 2)
581
+ key_states = key_states.transpose(1, 2)
582
+ value_states = value_states.transpose(1, 2)
583
+
584
+ dropout_rate = self.attention_dropout if self.training else 0.0
585
+
586
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
587
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
588
+ # cast them back in the correct dtype just to be sure everything works as expected.
589
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
590
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
591
+
592
+ input_dtype = query_states.dtype
593
+ if input_dtype == torch.float32:
594
+ # Handle the case where the model is quantized
595
+ if hasattr(self.config, "_pre_quantization_dtype"):
596
+ target_dtype = self.config._pre_quantization_dtype
597
+ else:
598
+ target_dtype = self.q_proj.weight.dtype
599
+
600
+ logger.warning_once(
601
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
602
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
603
+ f" {target_dtype}."
604
+ )
605
+
606
+ query_states = query_states.to(target_dtype)
607
+ key_states = key_states.to(target_dtype)
608
+ value_states = value_states.to(target_dtype)
609
+
610
+ attn_output = self._flash_attention_forward(
611
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
612
+ )
613
+
614
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
615
+ attn_output = self.o_proj(attn_output)
616
+
617
+ if not output_attentions:
618
+ attn_weights = None
619
+
620
+ return attn_output, attn_weights, past_key_value
621
+
622
+ def _flash_attention_forward(
623
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
624
+ ):
625
+ """
626
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
627
+ first unpad the input, then computes the attention scores and pad the final attention scores.
628
+
629
+ Args:
630
+ query_states (`torch.Tensor`):
631
+ Input query states to be passed to Flash Attention API
632
+ key_states (`torch.Tensor`):
633
+ Input key states to be passed to Flash Attention API
634
+ value_states (`torch.Tensor`):
635
+ Input value states to be passed to Flash Attention API
636
+ attention_mask (`torch.Tensor`):
637
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
638
+ position of padding tokens and 1 for the position of non-padding tokens.
639
+ dropout (`int`, *optional*):
640
+ Attention dropout
641
+ softmax_scale (`float`, *optional*):
642
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
643
+ """
644
+ if not self._flash_attn_uses_top_left_mask:
645
+ causal = self.is_causal
646
+ else:
647
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MiniCPMFlashAttention2 __init__.
648
+ causal = self.is_causal and query_length != 1
649
+ # Contains at least one padding token in the sequence
650
+ if attention_mask is not None:
651
+ batch_size = query_states.shape[0]
652
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
653
+ query_states, key_states, value_states, attention_mask, query_length
654
+ )
655
+
656
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
657
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
658
+ attn_output_unpad = flash_attn_varlen_func(
659
+ query_states,
660
+ key_states,
661
+ value_states,
662
+ cu_seqlens_q=cu_seqlens_q,
663
+ cu_seqlens_k=cu_seqlens_k,
664
+ max_seqlen_q=max_seqlen_in_batch_q,
665
+ max_seqlen_k=max_seqlen_in_batch_k,
666
+ dropout_p=dropout,
667
+ softmax_scale=softmax_scale,
668
+ causal=causal,
669
+ )
670
+
671
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
672
+ else:
673
+ attn_output = flash_attn_func(
674
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
675
+ )
676
+
677
+ return attn_output
678
+
679
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
680
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
681
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
682
+
683
+ key_layer = index_first_axis(
684
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
685
+ )
686
+ value_layer = index_first_axis(
687
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
688
+ )
689
+ if query_length == kv_seq_len:
690
+ query_layer = index_first_axis(
691
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
692
+ )
693
+ cu_seqlens_q = cu_seqlens_k
694
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
695
+ indices_q = indices_k
696
+ elif query_length == 1:
697
+ max_seqlen_in_batch_q = 1
698
+ cu_seqlens_q = torch.arange(
699
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
700
+ ) # There is a memcpy here, that is very bad.
701
+ indices_q = cu_seqlens_q[:-1]
702
+ query_layer = query_layer.squeeze(1)
703
+ else:
704
+ # The -q_len: slice assumes left padding.
705
+ attention_mask = attention_mask[:, -query_length:]
706
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
707
+
708
+ return (
709
+ query_layer,
710
+ key_layer,
711
+ value_layer,
712
+ indices_q,
713
+ (cu_seqlens_q, cu_seqlens_k),
714
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
715
+ )
716
+
717
+
718
+ class MiniCPMSdpaAttention(MiniCPMAttention):
719
+ """
720
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
721
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
722
+ SDPA API.
723
+ """
724
+
725
+ # Adapted from MiniCPMAttention.forward
726
+ def forward(
727
+ self,
728
+ hidden_states: torch.Tensor,
729
+ attention_mask: Optional[torch.Tensor] = None,
730
+ position_ids: Optional[torch.LongTensor] = None,
731
+ past_key_value: Optional[Cache] = None,
732
+ output_attentions: bool = False,
733
+ use_cache: bool = False,
734
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
735
+ if output_attentions:
736
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
737
+ logger.warning_once(
738
+ "MiniCPMModel is using MiniCPMSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
739
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
740
+ )
741
+ return super().forward(
742
+ hidden_states=hidden_states,
743
+ attention_mask=attention_mask,
744
+ position_ids=position_ids,
745
+ past_key_value=past_key_value,
746
+ output_attentions=output_attentions,
747
+ use_cache=use_cache,
748
+ )
749
+
750
+ bsz, q_len, _ = hidden_states.size()
751
+
752
+ query_states = self.q_proj(hidden_states)
753
+ key_states = self.k_proj(hidden_states)
754
+ value_states = self.v_proj(hidden_states)
755
+
756
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
757
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
758
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
759
+
760
+ kv_seq_len = key_states.shape[-2]
761
+ if past_key_value is not None:
762
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
763
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
764
+
765
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
766
+
767
+ if past_key_value is not None:
768
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
769
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
770
+
771
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
772
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
773
+
774
+ if attention_mask is not None:
775
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
776
+ raise ValueError(
777
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
778
+ )
779
+
780
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
781
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
782
+ if query_states.device.type == "cuda" and attention_mask is not None:
783
+ query_states = query_states.contiguous()
784
+ key_states = key_states.contiguous()
785
+ value_states = value_states.contiguous()
786
+
787
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
788
+ query_states,
789
+ key_states,
790
+ value_states,
791
+ attn_mask=attention_mask,
792
+ dropout_p=self.attention_dropout if self.training else 0.0,
793
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
794
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
795
+ )
796
+
797
+ attn_output = attn_output.transpose(1, 2).contiguous()
798
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
799
+
800
+ attn_output = self.o_proj(attn_output)
801
+
802
+ return attn_output, None, past_key_value
803
+
804
+
805
+ MINICPM_ATTENTION_CLASSES = {
806
+ "eager": MiniCPMAttention,
807
+ "flash_attention_2": MiniCPMFlashAttention2,
808
+ "sdpa": MiniCPMSdpaAttention,
809
+ }
810
+
811
+
812
+ class MiniCPMDecoderLayer(nn.Module):
813
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
814
+ super().__init__()
815
+ self.hidden_size = config.hidden_size
816
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
817
+
818
+ self.mlp = MiniCPMMLP(config)
819
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
820
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
821
+
822
+ self.scale_depth = config.scale_depth
823
+ self.num_hidden_layers = config.num_hidden_layers
824
+
825
+ def forward(
826
+ self,
827
+ hidden_states: torch.Tensor,
828
+ attention_mask: Optional[torch.Tensor] = None,
829
+ position_ids: Optional[torch.LongTensor] = None,
830
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
831
+ output_attentions: Optional[bool] = False,
832
+ use_cache: Optional[bool] = False,
833
+ **kwargs,
834
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
835
+ """
836
+ Args:
837
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
838
+ attention_mask (`torch.FloatTensor`, *optional*):
839
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
840
+ query_sequence_length, key_sequence_length)` if default attention is used.
841
+ output_attentions (`bool`, *optional*):
842
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
843
+ returned tensors for more detail.
844
+ use_cache (`bool`, *optional*):
845
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
846
+ (see `past_key_values`).
847
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
848
+ """
849
+ if "padding_mask" in kwargs:
850
+ warnings.warn(
851
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
852
+ )
853
+
854
+ residual = hidden_states
855
+ hidden_states = self.input_layernorm(hidden_states)
856
+ # Self Attention
857
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
858
+ hidden_states=hidden_states,
859
+ attention_mask=attention_mask,
860
+ position_ids=position_ids,
861
+ past_key_value=past_key_value,
862
+ output_attentions=output_attentions,
863
+ use_cache=use_cache,
864
+ **kwargs,
865
+ )
866
+
867
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
868
+
869
+ # Fully Connected
870
+ residual = hidden_states
871
+ hidden_states = self.post_attention_layernorm(hidden_states)
872
+
873
+ hidden_states = self.mlp(hidden_states)
874
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
875
+
876
+ outputs = (hidden_states,)
877
+
878
+ if output_attentions:
879
+ outputs += (self_attn_weights,)
880
+
881
+ if use_cache:
882
+ outputs += (present_key_value,)
883
+
884
+ return outputs
885
+
886
+
887
+ MINICPM_START_DOCSTRING = r"""
888
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
889
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
890
+ etc.)
891
+
892
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
893
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
894
+ and behavior.
895
+
896
+ Parameters:
897
+ config ([`MiniCPMConfig`]):
898
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
899
+ load the weights associated with the model, only the configuration. Check out the
900
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
901
+ """
902
+
903
+
904
+ @add_start_docstrings(
905
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
906
+ MINICPM_START_DOCSTRING,
907
+ )
908
+ class MiniCPMPreTrainedModel(PreTrainedModel):
909
+ config_class = MiniCPMConfig
910
+ base_model_prefix = "model"
911
+ supports_gradient_checkpointing = True
912
+ _no_split_modules = ["MiniCPMDecoderLayer"]
913
+ _skip_keys_device_placement = "past_key_values"
914
+ _supports_flash_attn_2 = True
915
+ _supports_sdpa = True
916
+ _supports_cache_class = True
917
+
918
+ def _init_weights(self, module):
919
+ std = self.config.initializer_range
920
+ if isinstance(module, nn.Linear):
921
+ module.weight.data.normal_(mean=0.0, std=std)
922
+ if module.bias is not None:
923
+ module.bias.data.zero_()
924
+ elif isinstance(module, nn.Embedding):
925
+ module.weight.data.normal_(mean=0.0, std=std)
926
+ if module.padding_idx is not None:
927
+ module.weight.data[module.padding_idx].zero_()
928
+
929
+
930
+ MINICPM_INPUTS_DOCSTRING = r"""
931
+ Args:
932
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
933
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
934
+ it.
935
+
936
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
937
+ [`PreTrainedTokenizer.__call__`] for details.
938
+
939
+ [What are input IDs?](../glossary#input-ids)
940
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
941
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
942
+
943
+ - 1 for tokens that are **not masked**,
944
+ - 0 for tokens that are **masked**.
945
+
946
+ [What are attention masks?](../glossary#attention-mask)
947
+
948
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
949
+ [`PreTrainedTokenizer.__call__`] for details.
950
+
951
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
952
+ `past_key_values`).
953
+
954
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
955
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
956
+ information on the default strategy.
957
+
958
+ - 1 indicates the head is **not masked**,
959
+ - 0 indicates the head is **masked**.
960
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
961
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
962
+ config.n_positions - 1]`.
963
+
964
+ [What are position IDs?](../glossary#position-ids)
965
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
966
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
967
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
968
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
969
+
970
+ Two formats are allowed:
971
+ - a [`~cache_utils.Cache`] instance;
972
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
973
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
974
+ cache format.
975
+
976
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
977
+ legacy cache format will be returned.
978
+
979
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
980
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
981
+ of shape `(batch_size, sequence_length)`.
982
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
983
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
984
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
985
+ model's internal embedding lookup matrix.
986
+ use_cache (`bool`, *optional*):
987
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
988
+ `past_key_values`).
989
+ output_attentions (`bool`, *optional*):
990
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
991
+ tensors for more detail.
992
+ output_hidden_states (`bool`, *optional*):
993
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
994
+ more detail.
995
+ return_dict (`bool`, *optional*):
996
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
997
+ """
998
+
999
+
1000
+ @add_start_docstrings(
1001
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
1002
+ MINICPM_START_DOCSTRING,
1003
+ )
1004
+ class MiniCPMModel(MiniCPMPreTrainedModel):
1005
+ """
1006
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
1007
+
1008
+ Args:
1009
+ config: MiniCPMConfig
1010
+ """
1011
+
1012
+ def __init__(self, config: MiniCPMConfig):
1013
+ super().__init__(config)
1014
+ self.padding_idx = config.pad_token_id
1015
+ self.vocab_size = config.vocab_size
1016
+
1017
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1018
+ self.layers = nn.ModuleList(
1019
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1020
+ )
1021
+ self._use_sdpa = config._attn_implementation == "sdpa"
1022
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1023
+
1024
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1025
+
1026
+ self.gradient_checkpointing = False
1027
+ self.is_causal = config.is_causal
1028
+ self.adapt_mean_pooling = config.adapt_mean_pooling
1029
+
1030
+ # Initialize weights and apply final processing
1031
+ self.head = torch.nn.Linear(in_features=1024, out_features=1, bias=False).float()
1032
+ self.post_init()
1033
+ self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path, trust_remote_code=True)
1034
+
1035
+ def get_input_embeddings(self):
1036
+ return self.embed_tokens
1037
+
1038
+ def set_input_embeddings(self, value):
1039
+ self.embed_tokens = value
1040
+
1041
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1042
+ def forward(
1043
+ self,
1044
+ input_ids: torch.LongTensor = None,
1045
+ attention_mask: Optional[torch.Tensor] = None,
1046
+ position_ids: Optional[torch.LongTensor] = None,
1047
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1048
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1049
+ use_cache: Optional[bool] = None,
1050
+ output_attentions: Optional[bool] = None,
1051
+ output_hidden_states: Optional[bool] = None,
1052
+ return_dict: Optional[bool] = None,
1053
+ adapt_mean_pooling: Optional[bool] = None,
1054
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1055
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1056
+ output_hidden_states = (
1057
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1058
+ )
1059
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1060
+
1061
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1062
+
1063
+ # retrieve input_ids and inputs_embeds
1064
+ if input_ids is not None and inputs_embeds is not None:
1065
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1066
+ elif input_ids is not None:
1067
+ batch_size, seq_length = input_ids.shape[:2]
1068
+ elif inputs_embeds is not None:
1069
+ batch_size, seq_length = inputs_embeds.shape[:2]
1070
+ else:
1071
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1072
+
1073
+ if self.gradient_checkpointing and self.training:
1074
+ if use_cache:
1075
+ logger.warning_once(
1076
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1077
+ )
1078
+ use_cache = False
1079
+
1080
+ past_key_values_length = 0
1081
+ if use_cache:
1082
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1083
+ if use_legacy_cache:
1084
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1085
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1086
+
1087
+ if position_ids is None:
1088
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1089
+ position_ids = torch.arange(
1090
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1091
+ )
1092
+ position_ids = position_ids.unsqueeze(0)
1093
+
1094
+ if inputs_embeds is None:
1095
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1096
+
1097
+ # print(attention_mask)
1098
+ _attention_mask = attention_mask
1099
+ if self._use_flash_attention_2:
1100
+ # 2d mask is passed through the layers
1101
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1102
+ elif self._use_sdpa and not output_attentions:
1103
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1104
+ # the manual implementation that requires a 4D causal mask in all cases.
1105
+ if self.is_causal:
1106
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa (
1107
+ attention_mask,
1108
+ (batch_size, seq_length),
1109
+ inputs_embeds,
1110
+ past_key_values_length,
1111
+ )
1112
+ else:
1113
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
1114
+ attention_mask,
1115
+ inputs_embeds.dtype,
1116
+ )
1117
+ else:
1118
+ # 4d mask is passed through the layers
1119
+ if self.is_causal:
1120
+ attention_mask = _prepare_4d_causal_attention_mask (
1121
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1122
+ )
1123
+ else:
1124
+ attention_mask = _prepare_4d_attention_mask(
1125
+ attention_mask,
1126
+ inputs_embeds.dtype,
1127
+ )
1128
+
1129
+ # embed positions
1130
+ hidden_states = inputs_embeds
1131
+
1132
+ # decoder layers
1133
+ all_hidden_states = () if output_hidden_states else None
1134
+ all_self_attns = () if output_attentions else None
1135
+ next_decoder_cache = None
1136
+
1137
+ for decoder_layer in self.layers:
1138
+ if output_hidden_states:
1139
+ all_hidden_states += (hidden_states,)
1140
+
1141
+ if self.gradient_checkpointing and self.training:
1142
+ layer_outputs = self._gradient_checkpointing_func(
1143
+ decoder_layer.__call__,
1144
+ hidden_states,
1145
+ attention_mask,
1146
+ position_ids,
1147
+ past_key_values,
1148
+ output_attentions,
1149
+ use_cache,
1150
+ )
1151
+ else:
1152
+ layer_outputs = decoder_layer(
1153
+ hidden_states,
1154
+ attention_mask=attention_mask,
1155
+ position_ids=position_ids,
1156
+ past_key_value=past_key_values,
1157
+ output_attentions=output_attentions,
1158
+ use_cache=use_cache,
1159
+ )
1160
+
1161
+ hidden_states = layer_outputs[0]
1162
+
1163
+ if use_cache:
1164
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1165
+
1166
+ if output_attentions:
1167
+ all_self_attns += (layer_outputs[1],)
1168
+
1169
+ hidden_states = self.norm(hidden_states)
1170
+
1171
+ # add hidden states from the last decoder layer
1172
+ if output_hidden_states:
1173
+ all_hidden_states += (hidden_states,)
1174
+
1175
+ next_cache = None
1176
+
1177
+ # gen weight before mean pooling
1178
+ if adapt_mean_pooling is None:
1179
+ adapt_mean_pooling = self.adapt_mean_pooling
1180
+ if adapt_mean_pooling:
1181
+ attention_mask_ = _attention_mask * _attention_mask.cumsum(dim=1)
1182
+ s = hidden_states * attention_mask_.unsqueeze(-1).float()
1183
+ d = attention_mask_.sum(dim=1, keepdim=True).unsqueeze(1).float() /_attention_mask.sum(dim=1, keepdim=True).unsqueeze(1).float()
1184
+
1185
+ hidden_states = s / d
1186
+
1187
+ if use_cache:
1188
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1189
+ if not return_dict:
1190
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1191
+
1192
+
1193
+
1194
+ return BaseModelOutputWithPast(
1195
+ last_hidden_state=hidden_states,
1196
+ past_key_values=next_cache,
1197
+ hidden_states=all_hidden_states,
1198
+ attentions=all_self_attns,
1199
+ )
1200
+
1201
+ @staticmethod
1202
+ def wmean_pooling(hidden,attention_mask):
1203
+ attention_mask_ = attention_mask * attention_mask.cumsum(dim=1)
1204
+ hidden_masked = hidden * attention_mask_.unsqueeze(-1).float()
1205
+ s = torch.sum(hidden_masked, dim=1)
1206
+ d = attention_mask_.sum(dim=1, keepdim=True).float()
1207
+ reps = s / d
1208
+ return reps
1209
+
1210
+
1211
+ def sparse_pooling(self,items, hidden, attention_mask):
1212
+ hidden = hidden * attention_mask.unsqueeze(-1).float()
1213
+ max_hidden_norm = torch.max(torch.norm(hidden,dim=-1),dim = -1).values.detach()
1214
+ token_weights = torch.relu(self.head(hidden.float()/max_hidden_norm.unsqueeze(-1).unsqueeze(-1)))
1215
+ vocab_size = self.embed_tokens.weight.size(0)
1216
+ input_ids = items["input_ids"]
1217
+ sparse_embedding_chunks = []
1218
+ mini_chunk_size = 1
1219
+ mini_chunk_size = min(mini_chunk_size,hidden.shape[0])
1220
+ for i in range(0, token_weights.size(0), mini_chunk_size):
1221
+ now_chunk_size = min(mini_chunk_size, token_weights.size(0) - i)
1222
+ sparse_embedding = torch.zeros(now_chunk_size , input_ids.size(1), vocab_size,
1223
+ dtype=token_weights.dtype,
1224
+ device=token_weights.device)
1225
+ sparse_embedding_chunks.append(torch.max((torch.scatter(sparse_embedding, dim=-1, index=input_ids[i:i+now_chunk_size, :].unsqueeze(-1), src=token_weights[i:i+now_chunk_size, :])), dim=1).values)
1226
+ sparse_embedding = torch.concat(sparse_embedding_chunks, dim=0)
1227
+ unused_tokens = [self.tokenizer.unk_token_id, self.tokenizer.pad_token_id, self.tokenizer.eos_token_id, self.tokenizer.bos_token_id]
1228
+ sparse_embedding[:,unused_tokens] = 0
1229
+ return sparse_embedding
1230
+
1231
+ @torch.no_grad()
1232
+ def process_sparse_embedding(self, sparse_embeddings,input_ids):
1233
+ results = []
1234
+ unused_tokens = [self.tokenizer.unk_token_id, self.tokenizer.pad_token_id, self.tokenizer.eos_token_id, self.tokenizer.bos_token_id]
1235
+ batch_size = sparse_embeddings.size(0)
1236
+ for i in range(batch_size):
1237
+ results.append({})
1238
+ for i, (sparse_embedding, input_id) in enumerate(zip(sparse_embeddings, input_ids)):
1239
+ for input_id_j in input_id.to(int).cpu().numpy().tolist():
1240
+ if input_id_j in unused_tokens:
1241
+ continue
1242
+ if sparse_embedding[input_id_j] == 0:
1243
+ continue
1244
+ results[i][self.tokenizer.convert_ids_to_tokens(input_id_j)] = sparse_embedding[input_id_j].item()
1245
+ return results
1246
+
1247
+ def encode(self,
1248
+ sentences: Union[str, List[str]],
1249
+ batch_size: int = 32,
1250
+ show_progress_bar: Optional[bool] = True,
1251
+ convert_to_numpy: bool = True,
1252
+ return_dense_vectors: bool = True,
1253
+ return_sparse_vectors: bool = False,
1254
+ max_length: int = 512,
1255
+ dense_dim: int = 1024,
1256
+ ):
1257
+ if isinstance(sentences, str):
1258
+ sentences = [sentences]
1259
+ dense_vectors_list = []
1260
+ sparse_vectors_list = []
1261
+ for start_index in tqdm(range(0, len(sentences), batch_size), desc="Batches", disable=not show_progress_bar):
1262
+ sentences_batch = sentences[start_index:start_index + batch_size]
1263
+ batch_dict = self.tokenizer(sentences_batch, padding=True, truncation=True, max_length=max_length, return_tensors="pt")
1264
+ for key in batch_dict:
1265
+ batch_dict[key] = batch_dict[key].to(self.device)
1266
+ outputs = self.forward(**batch_dict,adapt_mean_pooling=False)
1267
+ hidden_states = outputs.last_hidden_state
1268
+ attention_mask = batch_dict["attention_mask"]
1269
+ dense_vectors = None
1270
+ sparse_vectors = None
1271
+ if return_dense_vectors:
1272
+ dense_vectors = self.wmean_pooling(hidden_states,attention_mask)
1273
+ dense_vectors = F.normalize(dense_vectors[:,:dense_dim], p=2, dim=-1)
1274
+
1275
+ if convert_to_numpy:
1276
+ dense_vectors = dense_vectors.cpu().numpy()
1277
+ dense_vectors_list.append(dense_vectors)
1278
+ if return_sparse_vectors:
1279
+ sparse_vectors = self.sparse_pooling(batch_dict,hidden_states,attention_mask)
1280
+
1281
+ if convert_to_numpy:
1282
+ sparse_vectors = self.process_sparse_embedding(sparse_vectors, batch_dict["input_ids"])
1283
+ sparse_vectors_list.extend(sparse_vectors)
1284
+ else:
1285
+ sparse_vectors_list.append(sparse_vectors)
1286
+
1287
+ if convert_to_numpy:
1288
+ dense_vectors_list = np.concatenate(dense_vectors_list, axis=0)
1289
+ else:
1290
+ dense_vectors_list = torch.cat(dense_vectors_list, dim=0)
1291
+ sparse_vectors_list = torch.cat(sparse_vectors_list, dim=0)
1292
+ if len(sparse_vectors_list) == 0:
1293
+ sparse_vectors_list = None
1294
+ if len(dense_vectors_list) == 0:
1295
+ dense_vectors_list = None
1296
+ return dense_vectors_list, sparse_vectors_list
1297
+
1298
+
1299
+ """Compute similarity scores between queries and documents using dense and/or sparse embeddings.
1300
+
1301
+ This method computes similarity scores between query-document pairs using a combination of dense and sparse embeddings.
1302
+ It supports both single strings and lists of strings as input.
1303
+
1304
+ Args:
1305
+ queries (Union[str, List[str]]): Query text or list of query texts
1306
+ documents (Union[str, List[str]]): Document text or list of document texts
1307
+ show_progress_bar (Optional[bool]): Whether to show progress bar during encoding. Defaults to True.
1308
+ batch_size (int): Batch size for encoding. Defaults to 32.
1309
+ query_instruction (str): Instruction prefix for query encoding. Defaults to "Query:".
1310
+ return_dense_score (bool): Whether to compute and return dense embedding similarity scores. Defaults to True.
1311
+ return_sparse_score (bool): Whether to compute and return sparse embedding similarity scores. Defaults to True.
1312
+ weight_for_sparse_score (float): Weight factor for sparse scores when computing mixed scores. Defaults to 0.3.
1313
+ max_length (int): Maximum sequence length for tokenization. Defaults to 512.
1314
+ dense_dim (int): Dimension of dense embeddings. Defaults to 1024.
1315
+
1316
+ Returns:
1317
+ Tuple containing:
1318
+ dense_score (numpy.ndarray or None): Dense similarity scores if return_dense_score is True, else None
1319
+ sparse_score (numpy.ndarray or None): Sparse similarity scores if return_sparse_score is True, else None
1320
+ mix_score (numpy.ndarray or None): Weighted combination of dense and sparse scores if both are computed, else None
1321
+
1322
+ Note:
1323
+ - Dense scores are computed using dot product between query and document embeddings
1324
+ - Sparse scores are computed in chunks to handle memory efficiently
1325
+ - Mix scores are computed as: weight_for_sparse_score * sparse_score + dense_score
1326
+ """
1327
+ @torch.no_grad()
1328
+ def compute_score(self,
1329
+ queries: Union[str, List[str]],
1330
+ documents: Union[str, List[str]],
1331
+ show_progress_bar: Optional[bool] = True,
1332
+ batch_size: int = 32,
1333
+ query_instruction:str = "Query:",
1334
+ return_dense_score: bool = True,
1335
+ return_sparse_score: bool = True,
1336
+ weight_for_sparse_score: float = 0.3,
1337
+ max_length: int = 512,
1338
+ dense_dim: int = 1024):
1339
+ query_embeddings_dense, query_embeddings_sparse = self.encode_query(queries, batch_size, show_progress_bar,
1340
+ convert_to_numpy=False,
1341
+ return_dense_vectors=return_dense_score,
1342
+ return_sparse_vectors=return_sparse_score,
1343
+ max_length=max_length,
1344
+ dense_dim=dense_dim,
1345
+ query_instruction=query_instruction,
1346
+ )
1347
+ corpus_embeddings_dense, corpus_embeddings_sparse = self.encode_corpus(documents, batch_size, show_progress_bar,
1348
+ convert_to_numpy=False,
1349
+ return_dense_vectors=return_dense_score,
1350
+ return_sparse_vectors=return_sparse_score,
1351
+ max_length=max_length,
1352
+ dense_dim=dense_dim,
1353
+ )
1354
+ dense_score = None
1355
+ sparse_score = None
1356
+ mix_score = None
1357
+ if return_dense_score:
1358
+ dense_score = query_embeddings_dense @ corpus_embeddings_dense.T
1359
+ dense_score = dense_score.cpu().numpy()
1360
+ if return_sparse_score:
1361
+ min_chunk_size = 1024
1362
+ for i in range(0, query_embeddings_sparse.size(0), min_chunk_size):
1363
+ now_chunk_size = min(min_chunk_size, query_embeddings_sparse.size(0) - i)
1364
+ sparse_score_now_chunk = None
1365
+ for j in range(0, corpus_embeddings_sparse.size(0), min_chunk_size):
1366
+ sparse_score_chunk = query_embeddings_sparse[i:i+now_chunk_size] @ corpus_embeddings_sparse[j:j+min_chunk_size].T
1367
+ if sparse_score_now_chunk is None:
1368
+ sparse_score_now_chunk = sparse_score_chunk
1369
+ else:
1370
+ sparse_score_now_chunk = torch.cat((sparse_score_now_chunk, sparse_score_chunk), dim=1)
1371
+ if sparse_score is None:
1372
+ sparse_score = sparse_score_now_chunk
1373
+ else:
1374
+ sparse_score = torch.cat((sparse_score, sparse_score_now_chunk), dim=0)
1375
+ sparse_score = sparse_score.cpu().numpy()
1376
+ if return_sparse_score and return_dense_score:
1377
+ mix_score = weight_for_sparse_score * sparse_score + dense_score
1378
+ return dense_score, sparse_score, mix_score
1379
+
1380
+
1381
+ """
1382
+ Encodes query sentences into vector representations.
1383
+
1384
+ Args:
1385
+ sentences (Union[str, List[str]]): Input query sentence(s) to encode. Can be a single string or list of strings.
1386
+ batch_size (int, optional): Batch size for processing. Defaults to 32.
1387
+ show_progress_bar (Optional[bool], optional): Whether to display a progress bar. Defaults to True.
1388
+ convert_to_numpy (bool, optional): Whether to convert outputs to numpy arrays. Defaults to True.
1389
+ return_dense_vectors (bool, optional): Whether to return dense vector representations. Defaults to True.
1390
+ return_sparse_vectors (bool, optional): Whether to return sparse vector representations. Defaults to False.
1391
+ max_length (int, optional): Maximum sequence length for tokenization. Defaults to 512.
1392
+ dense_dim (int, optional): Dimension of dense output vectors. Defaults to 1024.
1393
+ query_instruction (str, optional): Instruction prefix to prepend to queries. Defaults to "Query:".
1394
+
1395
+ Returns:
1396
+ Same output format as the encode() method, with vector representations of the input queries.
1397
+
1398
+ Notes:
1399
+ This is a no-grad operation that wraps the encode() method by prepending a query instruction
1400
+ to each input sentence before encoding.
1401
+ """
1402
+ @torch.no_grad()
1403
+ def encode_query(self,
1404
+ sentences: Union[str, List[str]],
1405
+ batch_size: int = 32,
1406
+ show_progress_bar: Optional[bool] = True,
1407
+ convert_to_numpy: bool = True,
1408
+ return_dense_vectors: bool = True,
1409
+ return_sparse_vectors: bool = False,
1410
+ max_length: int = 512,
1411
+ dense_dim: int = 1024,
1412
+ query_instruction:str = "Query:"
1413
+ ):
1414
+ new_sentences = [" ".join([query_instruction, sentence]) for sentence in sentences]
1415
+ return self.encode(new_sentences, batch_size, show_progress_bar, convert_to_numpy, return_dense_vectors, return_sparse_vectors, max_length, dense_dim)
1416
+
1417
+
1418
+ """Encodes a corpus of text sentences into vector representations.
1419
+
1420
+ This method provides a wrapper for the encode method, specifically designed for corpus encoding.
1421
+ It processes text input into dense and/or sparse vector representations suitable for semantic search
1422
+ and other NLP tasks.
1423
+
1424
+ Args:
1425
+ sentences (Union[str, List[str]]): Input text or list of texts to encode.
1426
+ batch_size (int, optional): Number of sentences to encode in each batch. Defaults to 32.
1427
+ show_progress_bar (bool, optional): Whether to display a progress bar during encoding.
1428
+ Defaults to True.
1429
+ convert_to_numpy (bool, optional): Whether to convert the output tensors to numpy arrays.
1430
+ Defaults to True.
1431
+ return_dense_vectors (bool, optional): Whether to return dense vector representations.
1432
+ Defaults to True.
1433
+ return_sparse_vectors (bool, optional): Whether to return sparse vector representations.
1434
+ Defaults to False.
1435
+ max_length (int, optional): Maximum length of input sequences. Texts will be truncated
1436
+ to this length. Defaults to 512.
1437
+ dense_dim (int, optional): Dimension of the dense output vectors. Defaults to 1024.
1438
+
1439
+ Returns:
1440
+ The encoded representations as specified by return_dense_vectors and return_sparse_vectors
1441
+ parameters. Output format matches that of the encode method.
1442
+
1443
+ Note:
1444
+ This method is decorated with @torch.no_grad() for inference-only operation,
1445
+ ensuring no gradients are computed during encoding.
1446
+ """
1447
+ @torch.no_grad()
1448
+ def encode_corpus(self,
1449
+ sentences: Union[str, List[str]],
1450
+ batch_size: int = 32,
1451
+ show_progress_bar: Optional[bool] = True,
1452
+ convert_to_numpy: bool = True,
1453
+ return_dense_vectors: bool = True,
1454
+ return_sparse_vectors: bool = False,
1455
+ max_length: int = 512,
1456
+ dense_dim: int = 1024,
1457
+ ):
1458
+ return self.encode(sentences, batch_size, show_progress_bar, convert_to_numpy, return_dense_vectors, return_sparse_vectors, max_length, dense_dim)
1459
+
1460
+ @staticmethod
1461
+ def compute_sparse_score_dicts(dicts_query, dicts_corpus):
1462
+ scores_list = []
1463
+ for dict_q in dicts_query:
1464
+ scores = []
1465
+ for dict_d in dicts_corpus:
1466
+ score = 0
1467
+ for key in dict_q:
1468
+ if key in dict_d:
1469
+ score += dict_q[key] * dict_d[key]
1470
+ scores.append(score)
1471
+ scores_list.append(deepcopy(scores))
1472
+ return np.array(scores_list)
1473
+
1474
+
1475
+
1476
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1477
+ _tied_weights_keys = ["lm_head.weight"]
1478
+
1479
+ def __init__(self, config):
1480
+ super().__init__(config)
1481
+ self.model = MiniCPMModel(config)
1482
+ self.vocab_size = config.vocab_size
1483
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1484
+
1485
+ # Initialize weights and apply final processing
1486
+ self.post_init()
1487
+
1488
+ def get_input_embeddings(self):
1489
+ return self.model.embed_tokens
1490
+
1491
+ def set_input_embeddings(self, value):
1492
+ self.model.embed_tokens = value
1493
+
1494
+ def get_output_embeddings(self):
1495
+ return self.lm_head
1496
+
1497
+ def set_output_embeddings(self, new_embeddings):
1498
+ self.lm_head = new_embeddings
1499
+
1500
+ def set_decoder(self, decoder):
1501
+ self.model = decoder
1502
+
1503
+ def get_decoder(self):
1504
+ return self.model
1505
+
1506
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1507
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1508
+ def forward(
1509
+ self,
1510
+ input_ids: torch.LongTensor = None,
1511
+ attention_mask: Optional[torch.Tensor] = None,
1512
+ position_ids: Optional[torch.LongTensor] = None,
1513
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1514
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1515
+ labels: Optional[torch.LongTensor] = None,
1516
+ use_cache: Optional[bool] = None,
1517
+ output_attentions: Optional[bool] = None,
1518
+ output_hidden_states: Optional[bool] = None,
1519
+ return_dict: Optional[bool] = None,
1520
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1521
+ r"""
1522
+ Args:
1523
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1524
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1525
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1526
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1527
+
1528
+ Returns:
1529
+
1530
+ Example:
1531
+
1532
+ ```python
1533
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1534
+
1535
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1536
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1537
+
1538
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1539
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1540
+
1541
+ >>> # Generate
1542
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1543
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1544
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1545
+ ```"""
1546
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1547
+ output_hidden_states = (
1548
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1549
+ )
1550
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1551
+
1552
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1553
+ outputs = self.model(
1554
+ input_ids=input_ids,
1555
+ attention_mask=attention_mask,
1556
+ position_ids=position_ids,
1557
+ past_key_values=past_key_values,
1558
+ inputs_embeds=inputs_embeds,
1559
+ use_cache=use_cache,
1560
+ output_attentions=output_attentions,
1561
+ output_hidden_states=output_hidden_states,
1562
+ return_dict=return_dict,
1563
+ )
1564
+
1565
+ hidden_states = outputs[0]
1566
+ if self.config.pretraining_tp > 1:
1567
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1568
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1569
+ logits = torch.cat(logits, dim=-1)
1570
+ else:
1571
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1572
+ logits = logits.float()
1573
+
1574
+ loss = None
1575
+ if labels is not None:
1576
+ # Shift so that tokens < n predict n
1577
+ shift_logits = logits[..., :-1, :].contiguous()
1578
+ shift_labels = labels[..., 1:].contiguous()
1579
+ # Flatten the tokens
1580
+ loss_fct = CrossEntropyLoss()
1581
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1582
+ shift_labels = shift_labels.view(-1)
1583
+ # Enable model parallelism
1584
+ shift_labels = shift_labels.to(shift_logits.device)
1585
+ loss = loss_fct(shift_logits, shift_labels)
1586
+
1587
+ if not return_dict:
1588
+ output = (logits,) + outputs[1:]
1589
+ return (loss,) + output if loss is not None else output
1590
+
1591
+ return CausalLMOutputWithPast(
1592
+ loss=loss,
1593
+ logits=logits,
1594
+ past_key_values=outputs.past_key_values,
1595
+ hidden_states=outputs.hidden_states,
1596
+ attentions=outputs.attentions,
1597
+ )
1598
+
1599
+ def prepare_inputs_for_generation(
1600
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1601
+ ):
1602
+ if past_key_values is not None:
1603
+ if isinstance(past_key_values, Cache):
1604
+ cache_length = past_key_values.get_seq_length()
1605
+ past_length = past_key_values.seen_tokens
1606
+ max_cache_length = past_key_values.get_max_length()
1607
+ else:
1608
+ cache_length = past_length = past_key_values[0][0].shape[2]
1609
+ max_cache_length = None
1610
+
1611
+ # Keep only the unprocessed tokens:
1612
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1613
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1614
+ # input)
1615
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1616
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1617
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1618
+ # input_ids based on the past_length.
1619
+ elif past_length < input_ids.shape[1]:
1620
+ input_ids = input_ids[:, past_length:]
1621
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1622
+
1623
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1624
+ if (
1625
+ max_cache_length is not None
1626
+ and attention_mask is not None
1627
+ and cache_length + input_ids.shape[1] > max_cache_length
1628
+ ):
1629
+ attention_mask = attention_mask[:, -max_cache_length:]
1630
+
1631
+ position_ids = kwargs.get("position_ids", None)
1632
+ if attention_mask is not None and position_ids is None:
1633
+ # create position_ids on the fly for batch generation
1634
+ position_ids = attention_mask.long().cumsum(-1) - 1
1635
+ position_ids.masked_fill_(attention_mask == 0, 1)
1636
+ if past_key_values:
1637
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1638
+
1639
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1640
+ if inputs_embeds is not None and past_key_values is None:
1641
+ model_inputs = {"inputs_embeds": inputs_embeds}
1642
+ else:
1643
+ model_inputs = {"input_ids": input_ids}
1644
+
1645
+ model_inputs.update(
1646
+ {
1647
+ "position_ids": position_ids,
1648
+ "past_key_values": past_key_values,
1649
+ "use_cache": kwargs.get("use_cache"),
1650
+ "attention_mask": attention_mask,
1651
+ }
1652
+ )
1653
+ return model_inputs
1654
+
1655
+ @staticmethod
1656
+ def _reorder_cache(past_key_values, beam_idx):
1657
+ reordered_past = ()
1658
+ for layer_past in past_key_values:
1659
+ reordered_past += (
1660
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1661
+ )
1662
+ return reordered_past
1663
+
1664
+ @torch.inference_mode()
1665
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
1666
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1667
+ **kwargs):
1668
+ if history is None:
1669
+ history = []
1670
+ if logits_processor:
1671
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1672
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1673
+ else:
1674
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1675
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1676
+
1677
+ history.append({"role": role, "content": query})
1678
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1679
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1680
+ outputs = self.generate(**inputs, **gen_kwargs)
1681
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1682
+ response = tokenizer.decode(outputs)
1683
+ pattern = re.compile(r".*?(?=<AI>|<用户>)", re.DOTALL)
1684
+ matches = pattern.findall(response)
1685
+ if len(matches) > 0:
1686
+ response = matches[0]
1687
+ history.append({"role": "assistant", "content": response})
1688
+ return response, history
1689
+
1690
+
1691
+ @add_start_docstrings(
1692
+ """
1693
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1694
+
1695
+ [`MiniCPMForSequenceClassification`] uses the first token in order to do the classification, as other models
1696
+ (e.g. Roberta) do.
1697
+ """,
1698
+ MINICPM_START_DOCSTRING,
1699
+ )
1700
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1701
+ def __init__(self, config):
1702
+ super().__init__(config)
1703
+ self.num_labels = config.num_labels
1704
+ self.model = MiniCPMModel(config)
1705
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1706
+
1707
+ # Initialize weights and apply final processing
1708
+ self.post_init()
1709
+
1710
+ def get_input_embeddings(self):
1711
+ return self.model.embed_tokens
1712
+
1713
+ def set_input_embeddings(self, value):
1714
+ self.model.embed_tokens = value
1715
+
1716
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1717
+ def forward(
1718
+ self,
1719
+ input_ids: torch.LongTensor = None,
1720
+ attention_mask: Optional[torch.Tensor] = None,
1721
+ position_ids: Optional[torch.LongTensor] = None,
1722
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1723
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1724
+ labels: Optional[torch.LongTensor] = None,
1725
+ use_cache: Optional[bool] = None,
1726
+ output_attentions: Optional[bool] = None,
1727
+ output_hidden_states: Optional[bool] = None,
1728
+ return_dict: Optional[bool] = None,
1729
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1730
+ r"""
1731
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1732
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1733
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1734
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1735
+ """
1736
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1737
+
1738
+ transformer_outputs = self.model(
1739
+ input_ids,
1740
+ attention_mask=attention_mask,
1741
+ position_ids=position_ids,
1742
+ past_key_values=past_key_values,
1743
+ inputs_embeds=inputs_embeds,
1744
+ use_cache=use_cache,
1745
+ output_attentions=output_attentions,
1746
+ output_hidden_states=output_hidden_states,
1747
+ return_dict=return_dict,
1748
+ )
1749
+ hidden_states = transformer_outputs[0]
1750
+ # logits = self.score(hidden_states)
1751
+ logits = self.score(hidden_states[:,0,:])
1752
+ pooled_logits = logits
1753
+
1754
+ # if input_ids is not None:
1755
+ # batch_size = input_ids.shape[0]
1756
+ # else:
1757
+ # batch_size = inputs_embeds.shape[0]
1758
+
1759
+ # if self.config.pad_token_id is None and batch_size != 1:
1760
+ # raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1761
+ # if self.config.pad_token_id is None:
1762
+ # sequence_lengths = -1
1763
+ # else:
1764
+ # if input_ids is not None:
1765
+ # sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1766
+ # logits.device
1767
+ # )
1768
+ # else:
1769
+ # sequence_lengths = -1
1770
+
1771
+ # pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1772
+
1773
+ loss = None
1774
+ # if labels is not None:
1775
+ # labels = labels.to(logits.device)
1776
+ # if self.config.problem_type is None:
1777
+ # if self.num_labels == 1:
1778
+ # self.config.problem_type = "regression"
1779
+ # elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1780
+ # self.config.problem_type = "single_label_classification"
1781
+ # else:
1782
+ # self.config.problem_type = "multi_label_classification"
1783
+
1784
+ # if self.config.problem_type == "regression":
1785
+ # loss_fct = MSELoss()
1786
+ # if self.num_labels == 1:
1787
+ # loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1788
+ # else:
1789
+ # loss = loss_fct(pooled_logits, labels)
1790
+ # elif self.config.problem_type == "single_label_classification":
1791
+ # loss_fct = CrossEntropyLoss()
1792
+ # loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1793
+ # elif self.config.problem_type == "multi_label_classification":
1794
+ # loss_fct = BCEWithLogitsLoss()
1795
+ # loss = loss_fct(pooled_logits, labels)
1796
+ # if not return_dict:
1797
+ # output = (pooled_logits,) + transformer_outputs[1:]
1798
+ # return ((loss,) + output) if loss is not None else output
1799
+
1800
+ return SequenceClassifierOutputWithPast(
1801
+ loss=loss,
1802
+ logits=pooled_logits,
1803
+ past_key_values=transformer_outputs.past_key_values,
1804
+ hidden_states=transformer_outputs.hidden_states,
1805
+ attentions=transformer_outputs.attentions,
1806
+ )
modules.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ },
14
+ {
15
+ "idx": 2,
16
+ "name": "2",
17
+ "path": "2_Normalize",
18
+ "type": "sentence_transformers.models.Normalize"
19
+ }
20
+ ]
results/dense.md ADDED
The diff for this file is too large to render. See raw diff
 
results/dense_sparse.md ADDED
The diff for this file is too large to render. See raw diff
 
results/sparse.md ADDED
The diff for this file is too large to render. See raw diff
 
scripts/flagembedding_demo.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from FlagEmbedding import FlagModel
2
+
3
+
4
+ model = FlagModel("openbmb/UltraRAG-Embedding",
5
+ query_instruction_for_retrieval="Query: ",
6
+ pooling_method="mean",
7
+ trust_remote_code=True,
8
+ normalize_embeddings=True,
9
+ use_fp16=True)
10
+ # You can hack the __init__() method of the FlagEmbedding BaseEmbedder class to use flash_attention_2 for faster inference
11
+ # self.model = AutoModel.from_pretrained(
12
+ # model_name_or_path,
13
+ # trust_remote_code=trust_remote_code,
14
+ # cache_dir=cache_dir,
15
+ # # torch_dtype=torch.float16, # we need to add this line to use fp16
16
+ # # attn_implementation="flash_attention_2", # we need to add this line to use flash_attention_2
17
+ # )
18
+
19
+ queries = ["中国的首都是哪里?"] # "What is the capital of China?"
20
+ passages = ["beijing", "shanghai"] # "北京", "上海"
21
+
22
+
23
+ embeddings_query = model.encode_queries(queries)
24
+ embeddings_doc = model.encode_corpus(passages)
25
+
26
+ scores = (embeddings_query @ embeddings_doc.T)
27
+ print(scores.tolist()) # [[0.40356746315956116, 0.36183440685272217]]
scripts/infinity_demo.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from infinity_emb import AsyncEngineArray, EngineArgs, AsyncEmbeddingEngine
3
+ import numpy as np
4
+
5
+ array = AsyncEngineArray.from_args([
6
+ EngineArgs(model_name_or_path = "OpenBMB/UltraRAG-Embedding", engine="torch", dtype="float16", bettertransformer=False, pooling_method="mean", trust_remote_code=True),
7
+ ])
8
+ queries = ["中国的首都是哪里?"] # "What is the capital of China?"
9
+ passages = ["beijing", "shanghai"] # "北京", "上海"
10
+
11
+ INSTRUCTION = "Query:"
12
+ queries = [f"{INSTRUCTION} {query}" for query in queries]
13
+
14
+
15
+ async def embed_text(engine: AsyncEmbeddingEngine,sentences):
16
+ async with engine:
17
+ embeddings, usage = await engine.embed(sentences=sentences)
18
+ return embeddings
19
+
20
+ queries_embedding = asyncio.run(embed_text(array[0],queries))
21
+ passages_embedding = asyncio.run(embed_text(array[0],passages))
22
+
23
+ scores = (np.array(queries_embedding) @ np.array(passages_embedding).T)
24
+ print(scores.tolist()) # [[0.40356746315956116, 0.36183443665504456]]
scripts/sentence_transformers_demo.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from sentence_transformers import SentenceTransformer
3
+
4
+
5
+ model_name = "openbmb/UltraRAG-Embedding"
6
+ model = SentenceTransformer(model_name, trust_remote_code=True, model_kwargs={"torch_dtype": torch.float16})
7
+
8
+ # you can use flash_attention_2 for faster inference
9
+ # model = SentenceTransformer(model_name, trust_remote_code=True, model_kwargs={"attn_implementation": "flash_attention_2", "torch_dtype": torch.float16})
10
+
11
+ queries = ["中国的首都是哪里?"] # "What is the capital of China?"
12
+ passages = ["beijing", "shanghai"] # "北京", "上海"
13
+
14
+ INSTRUCTION = "Query: "
15
+
16
+ embeddings_query = model.encode(queries, prompt=INSTRUCTION)
17
+ embeddings_doc = model.encode(passages)
18
+
19
+ scores = (embeddings_query @ embeddings_doc.T)
20
+ print(scores.tolist()) # [[0.40356746315956116, 0.36183440685272217]]
scripts/test_mteb.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # copy from https://huggingface.co/Alibaba-NLP/gte-Qwen2-1.5B-instruct/blob/main/scripts/eval_mteb.py
2
+
3
+ #### ATTENTION ####
4
+ # To Reproduce the results of Sparse and Dense + Sparse, you need to hack the MTEB RetrievalEvaluator
5
+ # in mteb/evaluation/evaluators/RetrievalEvaluator.py
6
+ # class RetrievalEvaluator(Evaluator):
7
+ # def __init__(
8
+ # self,
9
+ # retriever=None,
10
+ # task_name: str | None = None,
11
+ # k_values: list[int] = [1, 3, 5, 10, 20, 100, 1000],
12
+ # score_function: str = "cos_sim",
13
+ # encode_kwargs: dict[str, Any] = {},
14
+ # **kwargs,
15
+ # ):
16
+ # you need to change default score_function to "dot" to reproduce the results of Sparse and Dense + Sparse
17
+ MODE = "Dense" # "Dense" or "Sparse" or "Dense + Sparse"
18
+
19
+ TASK_LIST_CLASSIFICATION = [
20
+ "AmazonCounterfactualClassification",
21
+ "AmazonPolarityClassification",
22
+ "AmazonReviewsClassification",
23
+ "Banking77Classification",
24
+ "EmotionClassification",
25
+ "ImdbClassification",
26
+ "MassiveIntentClassification",
27
+ "MassiveScenarioClassification",
28
+ "MTOPDomainClassification",
29
+ "MTOPIntentClassification",
30
+ "ToxicConversationsClassification",
31
+ "TweetSentimentExtractionClassification",
32
+ ]
33
+
34
+ TASK_LIST_CLUSTERING = [
35
+ "ArxivClusteringP2P",
36
+ "ArxivClusteringS2S",
37
+ "BiorxivClusteringP2P",
38
+ "BiorxivClusteringS2S",
39
+ "MedrxivClusteringP2P",
40
+ "MedrxivClusteringS2S",
41
+ "RedditClustering",
42
+ "RedditClusteringP2P",
43
+ "StackExchangeClustering",
44
+ "StackExchangeClusteringP2P",
45
+ "TwentyNewsgroupsClustering",
46
+ ]
47
+
48
+ TASK_LIST_PAIR_CLASSIFICATION = [
49
+ "SprintDuplicateQuestions",
50
+ "TwitterSemEval2015",
51
+ "TwitterURLCorpus",
52
+ ]
53
+
54
+ TASK_LIST_RERANKING = [
55
+ "AskUbuntuDupQuestions",
56
+ "MindSmallReranking",
57
+ "SciDocsRR",
58
+ "StackOverflowDupQuestions",
59
+ ]
60
+
61
+ TASK_LIST_RETRIEVAL = [
62
+ "ArguAna",
63
+ "FiQA2018",
64
+ "QuoraRetrieval",
65
+ "SCIDOCS",
66
+ "SciFact",
67
+ "Touche2020",
68
+ "TRECCOVID",
69
+ "NFCorpus",
70
+ "NQ",
71
+ "ClimateFEVER",
72
+ "CQADupstackAndroidRetrieval",
73
+ "CQADupstackEnglishRetrieval",
74
+ "CQADupstackGamingRetrieval",
75
+ "CQADupstackGisRetrieval",
76
+ "CQADupstackMathematicaRetrieval",
77
+ "CQADupstackPhysicsRetrieval",
78
+ "CQADupstackProgrammersRetrieval",
79
+ "CQADupstackStatsRetrieval",
80
+ "CQADupstackTexRetrieval",
81
+ "CQADupstackUnixRetrieval",
82
+ "CQADupstackWebmastersRetrieval",
83
+ "CQADupstackWordpressRetrieval",
84
+ "DBPedia",
85
+ "HotpotQA",
86
+ "MSMARCO",
87
+ "FEVER",
88
+ ]
89
+
90
+ TASK_LIST_STS = [
91
+ "BIOSSES",
92
+ "SICK-R",
93
+ "STS12",
94
+ "STS13",
95
+ "STS14",
96
+ "STS15",
97
+ "STS16",
98
+ "STS17",
99
+ "STS22",
100
+ "STSBenchmark",
101
+ "SummEval",
102
+ ]
103
+
104
+ MTEB_TASK_LIST = (
105
+ TASK_LIST_RETRIEVAL
106
+ + TASK_LIST_CLASSIFICATION
107
+ + TASK_LIST_CLUSTERING
108
+ + TASK_LIST_PAIR_CLASSIFICATION
109
+ + TASK_LIST_RERANKING
110
+ + TASK_LIST_STS
111
+ )
112
+
113
+
114
+ CMTEB_TASK_LIST = [
115
+ "TNews",
116
+ "IFlyTek",
117
+ "MultilingualSentiment",
118
+ "JDReview",
119
+ "OnlineShopping",
120
+ "Waimai",
121
+ "AmazonReviewsClassification",
122
+ "MassiveIntentClassification",
123
+ "MassiveScenarioClassification",
124
+ "MultilingualSentiment",
125
+ "CLSClusteringS2S",
126
+ "CLSClusteringP2P",
127
+ "ThuNewsClusteringS2S",
128
+ "ThuNewsClusteringP2P",
129
+ "Ocnli",
130
+ "Cmnli",
131
+ "T2Reranking",
132
+ "MMarcoReranking",
133
+ "CMedQAv1-reranking",
134
+ "CMedQAv2-reranking",
135
+ "T2Retrieval",
136
+ "MMarcoRetrieval",
137
+ "DuRetrieval",
138
+ "CovidRetrieval",
139
+ "CmedqaRetrieval",
140
+ "EcomRetrieval",
141
+ "MedicalRetrieval",
142
+ "VideoRetrieval",
143
+ "ATEC",
144
+ "BQ",
145
+ "LCQMC",
146
+ "PAWSX",
147
+ "STSB",
148
+ "AFQMC",
149
+ "QBQTC",
150
+ "STS22",
151
+ ]
152
+
153
+ MTEB_TASK_LIST = CMTEB_TASK_LIST + MTEB_TASK_LIST
154
+
155
+ import torch
156
+ import torch.nn.functional as F
157
+ import tqdm
158
+ import numpy as np
159
+ import math
160
+
161
+ from functools import partial
162
+ from torch.utils.data import DataLoader
163
+ from datasets import Dataset
164
+ from transformers import AutoModel, AutoTokenizer, DataCollatorWithPadding, PreTrainedTokenizerFast, BatchEncoding
165
+ from transformers.modeling_outputs import BaseModelOutput
166
+ from typing import List, Dict
167
+ from mteb import MTEB
168
+
169
+ def get_detailed_instruct(task_description: str) -> str:
170
+ if not task_description:
171
+ return ""
172
+
173
+ return "Instruction: {} Query: ".format(task_description)
174
+
175
+
176
+
177
+ def get_task_def_by_task_name_and_type(
178
+ task_name: str,
179
+ task_type: str,
180
+ default_instruct="",
181
+ ):
182
+ if task_type in ["STS"]:
183
+ return None
184
+
185
+ if task_type in ["Summarization"]:
186
+ return "Given a news summary, retrieve other semantically similar summaries"
187
+
188
+ if task_type in ["Classification"]:
189
+ task_name_to_instruct: Dict[str, str] = {
190
+ "AmazonCounterfactualClassification": "Classify a given Amazon customer review text as either counterfactual or not-counterfactual.",
191
+ "AmazonPolarityClassification": "Classify Amazon reviews into positive or negative sentiment.",
192
+ "AmazonReviewsClassification": "Classify the given Amazon review into its appropriate rating category.",
193
+ "Banking77Classification": "Given a online banking query, find the corresponding intents.",
194
+ "EmotionClassification": "Classify the emotion expressed in the given Twitter message into one of the six emotions: anger, fear, joy, love, sadness, and surprise.",
195
+ "ImdbClassification": "Classify the sentiment expressed in the given movie review text from the IMDB dataset.",
196
+ "MassiveIntentClassification": "Given a user utterance as query, find the user intents.",
197
+ "MassiveScenarioClassification": "Given a user utterance as query, find the user scenarios.",
198
+ "MTOPDomainClassification": "Classify the intent domain of the given utterance in task-oriented conversation.",
199
+ "MTOPIntentClassification": "Classify the intent of the given utterance in task-oriented conversation.",
200
+ "ToxicConversationsClassification": "Classify the given comments as either toxic or not toxic.",
201
+ "TweetSentimentExtractionClassification": "Classify the sentiment of a given tweet as either positive, negative, or neutral.",
202
+ # C-MTEB eval instructions
203
+ "TNews": "根据标题确定新闻的类别。",
204
+ "IFlyTek": "根据描述确定APP的类别。",
205
+ "MultilingualSentiment": "将亚马逊评论分为积极、消极或中立情绪。",
206
+ "JDReview": "将商品评论分为积极或消极情绪。",
207
+ "OnlineShopping": "将商品评论分为积极或消极情绪。",
208
+ "Waimai": "将外卖评论分为积极或消极情绪。",
209
+ }
210
+ return task_name_to_instruct.get(task_name,None)
211
+
212
+ if task_type in ["Clustering"]:
213
+ task_name_to_instruct: Dict[str, str] = {
214
+ "ArxivClusteringP2P": "Identify the main and secondary category of Arxiv papers based on the titles and abstracts.",
215
+ "ArxivClusteringS2S": "Identify the main and secondary category of Arxiv papers based on the titles.",
216
+ "BiorxivClusteringP2P": "Identify the main category of Biorxiv papers based on the titles and abstracts.",
217
+ "BiorxivClusteringS2S": "Identify the main category of Biorxiv papers based on the titles.",
218
+ "MedrxivClusteringP2P": "Identify the main category of Medrxiv papers based on the titles and abstracts.",
219
+ "MedrxivClusteringS2S": "Identify the main category of Medrxiv papers based on the titles.",
220
+ "RedditClustering": "Identify the topic or theme of Reddit posts based on the titles.",
221
+ "RedditClusteringP2P": "Identify the topic or theme of Reddit posts based on the titles and posts.",
222
+ "StackExchangeClustering": "Identify the topic or theme of StackExchange posts based on the titles.",
223
+ "StackExchangeClusteringP2P": "Identify the topic or theme of StackExchange posts based on the given paragraphs.",
224
+ "TwentyNewsgroupsClustering": "Identify the topic or theme of the given news articles.",
225
+ # C-MTEB eval instructions
226
+ "CLSClusteringS2S": "根据标题确定文章的类别。",
227
+ "CLSClusteringP2P": "根据标题和摘要确定文章的类别。",
228
+ "ThuNewsClusteringS2S": "根据标题确定新闻的类别。",
229
+ "ThuNewsClusteringP2P": "根据标题和摘要确定新闻的类别。",
230
+ }
231
+ return task_name_to_instruct.get(task_name,None)
232
+
233
+ if task_type in ["Reranking", "PairClassification"]:
234
+ task_name_to_instruct: Dict[str, str] = {
235
+ "AskUbuntuDupQuestions": "Retrieve duplicate questions from AskUbuntu forum.",
236
+ "MindSmallReranking": "Retrieve relevant news articles based on user browsing history.",
237
+ "SciDocsRR": "Given a title of a scientific paper, retrieve the titles of other relevant papers.",
238
+ "StackOverflowDupQuestions": "Retrieve duplicate questions from StackOverflow forum.",
239
+ "SprintDuplicateQuestions": "Retrieve duplicate questions from Sprint forum.",
240
+ "TwitterSemEval2015": "Retrieve tweets that are semantically similar to the given tweet.",
241
+ "TwitterURLCorpus": "Retrieve tweets that are semantically similar to the given tweet.",
242
+ # C-MTEB eval instructions
243
+ "T2Reranking": "为这个问题检索相关段落。",
244
+ "MMarcoReranking": "为这个查询检索相关段落。",
245
+ "CMedQAv1-reranking": "为这个医疗问题检索相关回答。",
246
+ "CMedQAv2-reranking": "为这个医疗问题检索相关回答。",
247
+ }
248
+
249
+ return task_name_to_instruct.get(task_name,None)
250
+
251
+ if task_type in ["Retrieval"]:
252
+ if task_name.lower().startswith("cqadupstack"):
253
+ return "Given a question, retrieve detailed question descriptions from Stackexchange that are duplicates to the given question"
254
+
255
+ task_name_to_instruct: Dict[str, str] = {
256
+ "ArguAna": "Given a claim, find documents that refute the claim.",
257
+ "ClimateFEVER": "Given a claim about climate change, retrieve documents that support or refute the claim.",
258
+ "DBPedia": "Given a query, retrieve relevant entity descriptions from DBPedia.",
259
+ "FEVER": "Given a claim, retrieve documents that support or refute the claim.",
260
+ "FiQA2018": "Given a financial question, retrieve user replies that best answer the question.",
261
+ "HotpotQA": "Given a multi-hop question, retrieve documents that can help answer the question.",
262
+ "MSMARCO": "Given a web search query, retrieve relevant passages that answer the query.",
263
+ "NFCorpus": "Given a question, retrieve relevant documents that best answer the question.",
264
+ "NQ": "Given a question, retrieve Wikipedia passages that answer the question.",
265
+ "QuoraRetrieval": "Given a question, retrieve questions that are semantically equivalent to the given question.",
266
+ "SCIDOCS": "Given a scientific paper title, retrieve paper abstracts that are cited by the given paper.",
267
+ "SciFact": "Given a scientific claim, retrieve documents that support or refute the claim.",
268
+ "Touche2020": "Given a question, retrieve detailed and persuasive arguments that answer the question.",
269
+ "TRECCOVID": "Given a query on COVID-19, retrieve documents that answer the query.",
270
+ # C-MTEB eval instructions
271
+ "T2Retrieval": "为这个问题检索相关段落。",
272
+ "MMarcoRetrieval": "为这个查询检索相关段落。",
273
+ "DuRetrieval": "为这个问题检索相关百度知道回答。",
274
+ "CovidRetrieval": "为这个问题检索相关政策回答。",
275
+ "CmedqaRetrieval": "为这个医疗问题检索相关回答。",
276
+ "EcomRetrieval": "为这个查询检索相关商品标题。",
277
+ "MedicalRetrieval": "为这个医疗问题检索相关回答。",
278
+ "VideoRetrieval": "为这个电影标题检索相关段落。",
279
+ }
280
+
281
+ task_name_to_instruct.update({k.lower(): v for k, v in task_name_to_instruct.items()})
282
+
283
+ return task_name_to_instruct.get(task_name,None)
284
+ return default_instruct
285
+ def _transform_func(tokenizer: PreTrainedTokenizerFast,
286
+ examples: Dict[str, List]) -> BatchEncoding:
287
+ batch_dict = tokenizer(examples['input_texts'],
288
+ max_length=1024,
289
+ padding=True,
290
+ truncation=True)
291
+
292
+ return batch_dict
293
+
294
+ # def weighted_mean_pooling(hidden,attention_mask):
295
+ # # print(hidden.shape,attention_mask.shape)
296
+ # attention_mask_ = attention_mask * attention_mask.cumsum(dim=1)
297
+ # s = torch.sum(hidden * attention_mask_.unsqueeze(-1).float(), dim=1)
298
+ # d = attention_mask_.sum(dim=1, keepdim=True).float()
299
+ # reps = s / d
300
+ # return reps
301
+
302
+ def mean_pooling(hidden,attention_mask):
303
+ # print(hidden.shape,attention_mask.shape)
304
+ s = torch.sum(hidden * attention_mask.unsqueeze(-1).float(), dim=1)
305
+ d = attention_mask.sum(dim=1, keepdim=True).float()
306
+ return s / d
307
+
308
+ def wmean_pooling(hidden,attention_mask):
309
+ attention_mask_ = attention_mask * attention_mask.cumsum(dim=1)
310
+ hidden_masked = hidden * attention_mask_.unsqueeze(-1).float()
311
+ s = torch.sum(hidden_masked, dim=1)
312
+ d = attention_mask_.sum(dim=1, keepdim=True).float()
313
+ reps = s / d
314
+ return reps
315
+
316
+ def reverse_wmean_pooling(hidden,attention_mask):
317
+ attention_mask_ = attention_mask * attention_mask.cumsum(dim=1)
318
+ d = attention_mask_.sum(dim=1, keepdim=True).unsqueeze(1).float() / attention_mask.sum(dim=1, keepdim=True).unsqueeze(1).float()
319
+ hidden = hidden.float() * d
320
+ return hidden / torch.clamp(attention_mask_.unsqueeze(-1).float(),min=1e-9)
321
+
322
+
323
+ def sparse_pooling(head,model,items,hidden,attention_mask):
324
+ hidden = reverse_wmean_pooling(hidden,attention_mask) # reverse weighted mean pooling, beacuse the hidden states are modified in the model
325
+ max_hidden_norm = torch.max(torch.norm(hidden,dim=-1),dim = -1).values
326
+ token_weights = torch.relu(head(hidden.float()/max_hidden_norm.unsqueeze(-1).unsqueeze(-1)))
327
+ vocab_size = model.embed_tokens.weight.size(0)
328
+ input_ids = items["input_ids"]
329
+ sparse_embedding_chunks = []
330
+ mini_chunk_size = 1
331
+ mini_chunk_size = min(mini_chunk_size,hidden.shape[0])
332
+ for i in range(0, token_weights.size(0), mini_chunk_size):
333
+ now_chunk_size = min(mini_chunk_size, token_weights.size(0) - i)
334
+ sparse_embedding = torch.zeros(now_chunk_size , input_ids.size(1), vocab_size,
335
+ dtype=token_weights.dtype,
336
+ device=token_weights.device)
337
+ sparse_embedding_chunks.append(torch.max((torch.scatter(sparse_embedding, dim=-1, index=input_ids[i:i+now_chunk_size, :].unsqueeze(-1), src=token_weights[i:i+now_chunk_size, :])), dim=1).values)
338
+ sparse_embedding = torch.concat(sparse_embedding_chunks, dim=0)
339
+ unused_tokens = [0,1,2,73440]
340
+ sparse_embedding[:, unused_tokens] *= 0.
341
+ return sparse_embedding
342
+
343
+ def concat_pooling(head,model,items,hidden,attention_mask):
344
+ mean_reps = mean_pooling(hidden,attention_mask)
345
+ mean_reps = F.normalize(mean_reps, p=2, dim=1)
346
+ sparse_reps = sparse_pooling(head,model,items,hidden,attention_mask) * math.sqrt(0.3)
347
+ return torch.cat([mean_reps,sparse_reps],dim=-1)
348
+
349
+ #
350
+
351
+ class DenseEncoder(torch.nn.Module):
352
+ def __init__(self, **kwargs):
353
+ super().__init__()
354
+
355
+ model_path = "openbmb/UltraRAG-Embedding"
356
+ self.encoder = AutoModel.from_pretrained(model_path, trust_remote_code=True,attn_implementation="flash_attention_2", torch_dtype=torch.float16).to("cuda")
357
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
358
+ self.gpu_count = torch.cuda.device_count()
359
+ self.instruction = ""
360
+
361
+ self.encoder.eval()
362
+ self.encoder.cuda()
363
+
364
+ if self.gpu_count > 1:
365
+ self.encoder = torch.nn.DataParallel(self.encoder)
366
+
367
+ @torch.no_grad()
368
+ def encode(self, sentences,is_query=None, **kwargs) -> np.ndarray:
369
+ """ Returns a list of embeddings for the given sentences.
370
+ Args:
371
+ sentences (`List[str]`): List of sentences to encode
372
+ batch_size (`int`): Batch size for the encoding
373
+
374
+ Returns:
375
+ `List[np.ndarray]` or `List[tensor]`: List of embeddings for the given sentences
376
+ """
377
+ if is_query is not False:
378
+ sentences = [self.instruction + s for s in sentences]
379
+ dataset: Dataset = Dataset.from_dict({'input_texts': sentences})
380
+ # dataset: Dataset = Dataset.from_dict({'input_texts': ["Query: " + s for s in sentences]})
381
+
382
+ dataset.set_transform(partial(_transform_func, self.tokenizer))
383
+
384
+ data_collator = DataCollatorWithPadding(self.tokenizer, pad_to_multiple_of=8)
385
+ data_loader = DataLoader(
386
+ dataset,
387
+ batch_size=128* self.gpu_count,
388
+ shuffle=False,
389
+ drop_last=False,
390
+ num_workers=2,
391
+ collate_fn=data_collator,
392
+ pin_memory=True)
393
+
394
+ encoded_embeds = []
395
+ for batch_dict in tqdm.tqdm(data_loader, desc='encoding', mininterval=10):
396
+
397
+ with torch.cuda.amp.autocast() and torch.no_grad():
398
+ for key in batch_dict:
399
+ batch_dict[key] = batch_dict[key].to("cuda")
400
+ outputs: BaseModelOutput = self.encoder(**batch_dict)
401
+ if MODE == "Dense":
402
+ embeds = mean_pooling(outputs.last_hidden_state, batch_dict['attention_mask'])
403
+ embeds = F.normalize(embeds, p=2, dim=1)
404
+ elif MODE == "Sparse":
405
+ embeds = sparse_pooling(self.encoder.module.head,self.encoder.module, batch_dict, outputs.last_hidden_state, batch_dict['attention_mask'])
406
+ else:
407
+ embeds = concat_pooling(self.encoder.module.head,self.encoder.module, batch_dict, outputs.last_hidden_state, batch_dict['attention_mask'])
408
+ encoded_embeds.append(embeds.cpu().numpy())
409
+
410
+ return np.concatenate(encoded_embeds, axis=0)
411
+
412
+ @torch.no_grad()
413
+ def encode_queries(self, queries: list[str], **kwargs) -> list[np.ndarray] | list[torch.Tensor]:
414
+ """
415
+ Returns a list of embeddings for the given sentences.
416
+ Args:
417
+ queries: List of sentences to encode
418
+
419
+ Returns:
420
+ List of embeddings for the given sentences
421
+ """
422
+
423
+
424
+ queries = [query for query in queries]
425
+ return self.encode(queries, is_query=True, **kwargs)
426
+
427
+ @torch.no_grad()
428
+ def encode_corpus(self, corpus: List[Dict[str, str]], **kwargs):
429
+ # borrowed from mteb.abstasks.AbsTaskRetrieval.DRESModel
430
+ if type(corpus) is dict:
431
+ sentences = [
432
+ (corpus["title"][i] + " " + corpus["text"][i]).strip()
433
+ if "title" in corpus
434
+ else corpus["text"][i].strip()
435
+ for i in range(len(corpus["text"]))
436
+ ]
437
+ elif isinstance(corpus[0], dict):
438
+ sentences = [
439
+ (doc["title"] + " " + doc["text"]).strip()
440
+ if "title" in doc
441
+ else doc["text"].strip()
442
+ for doc in corpus
443
+ ]
444
+ else:
445
+ sentences = corpus
446
+ is_query = False
447
+ return self.encode(sentences, is_query=is_query, **kwargs)
448
+
449
+
450
+ model = DenseEncoder()
451
+ task_names = MTEB_TASK_LIST
452
+ task_names = ["NFCorpus"]
453
+ lang = ["en","zh", "zh-CN"]
454
+
455
+ for task in task_names:
456
+ try:
457
+ evaluation = MTEB(tasks=[task], task_langs=lang)
458
+ task_cls = evaluation.tasks[0]
459
+ task_name: str = task_cls.metadata_dict["name"]
460
+ task_type: str = task_cls.metadata_dict["type"]
461
+ instruction = get_task_def_by_task_name_and_type(task_name, task_type)
462
+ model.instruction = get_detailed_instruct(instruction)
463
+ print(model.instruction)
464
+ if task == "MSMARCO":
465
+ eval_splits = ["dev"]
466
+ elif task in CMTEB_TASK_LIST:
467
+ eval_splits = task_cls.metadata_dict["eval_splits"]
468
+ else:
469
+ eval_splits = ["test"]
470
+ evaluation.run(model, eval_splits=eval_splits, overwrite_results=True)
471
+
472
+ except Exception as e:
473
+ import traceback
474
+ print(traceback.format_exc())
475
+ continue
scripts/transformers_demo.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from transformers import AutoModel
3
+ import torch
4
+
5
+ model_name = "openbmb/UltraRAG-Embedding"
6
+ model = AutoModel.from_pretrained(model_name, trust_remote_code=True, torch_dtype=torch.float16).to("cuda")
7
+
8
+ # you can use flash_attention_2 for faster inference
9
+ # model = AutoModel.from_pretrained(model_name, trust_remote_code=True, attn_implementation="flash_attention_2", torch_dtype=torch.float16).to("cuda")
10
+
11
+ model.eval()
12
+
13
+ queries = ["MiniCPM-o 2.6 A GPT-4o Level MLLM for Vision, Speech and Multimodal Live Streaming on Your Phone"]
14
+ passages = ["MiniCPM-o 2.6 is the latest and most capable model in the MiniCPM-o series. The model is built in an end-to-end fashion based on SigLip-400M, Whisper-medium-300M, ChatTTS-200M, and Qwen2.5-7B with a total of 8B parameters. It exhibits a significant performance improvement over MiniCPM-V 2.6, and introduces new features for real-time speech conversation and multimodal live streaming."]
15
+
16
+ embeddings_query_dense, embeddings_query_sparse = model.encode_query(queries, return_sparse_vectors=True, max_length=8192, dense_dim=1024)
17
+ embeddings_doc_dense, embeddings_doc_sparse = model.encode_corpus(passages, return_sparse_vectors=True)
18
+
19
+ dense_scores = (embeddings_query_dense @ embeddings_doc_dense.T)
20
+ print(dense_scores.tolist()) # [[0.6512398719787598]]
21
+ print(model.compute_sparse_score_dicts(embeddings_query_sparse, embeddings_doc_sparse)) # [[0.27202296]]
22
+
23
+ dense_scores, sparse_scores, mixed_scores = model.compute_score(queries, passages)
24
+ print(dense_scores) # [[0.65123993]]
25
+ print(sparse_scores) # [[0.27202296]]
26
+ print(mixed_scores) # [[0.73284686]]
sentence_bert_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "max_seq_length": 8192
3
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_end|>",
4
+ "<|im_start|>",
5
+ "<|tool_call|>",
6
+ "<|execute_start|>",
7
+ "<|execute_end|>",
8
+ "<|fim_prefix|>",
9
+ "<|fim_middle|>",
10
+ "<|fim_suffix|>"
11
+ ],
12
+ "bos_token": {
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "eos_token": {
20
+ "content": "<|im_end|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "pad_token": {
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ },
33
+ "unk_token": {
34
+ "content": "<unk>",
35
+ "lstrip": false,
36
+ "normalized": false,
37
+ "rstrip": false,
38
+ "single_word": false
39
+ }
40
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb74d51116831c3bf65db812c553f94ab0c88dcf97a5bbb37e3504f6d359c530
3
+ size 1181204
tokenizer_config.json ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": true,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "73440": {
30
+ "content": "<|im_end|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "73441": {
38
+ "content": "<|im_start|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "73442": {
46
+ "content": "<|tool_call|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "73443": {
54
+ "content": "<|execute_start|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "73444": {
62
+ "content": "<|execute_end|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "73445": {
70
+ "content": "<|fim_prefix|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "73446": {
78
+ "content": "<|fim_middle|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "73447": {
86
+ "content": "<|fim_suffix|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ }
93
+ },
94
+ "additional_special_tokens": [
95
+ "<|im_end|>",
96
+ "<|im_start|>",
97
+ "<|tool_call|>",
98
+ "<|execute_start|>",
99
+ "<|execute_end|>",
100
+ "<|fim_prefix|>",
101
+ "<|fim_middle|>",
102
+ "<|fim_suffix|>"
103
+ ],
104
+ "bos_token": "<s>",
105
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
106
+ "clean_up_tokenization_spaces": false,
107
+ "eos_token": "<|im_end|>",
108
+ "legacy": true,
109
+ "model_max_length": 1000000000000000019884624838656,
110
+ "pad_token": "<unk>",
111
+ "sp_model_kwargs": {},
112
+ "spaces_between_special_tokens": false,
113
+ "tokenizer_class": "LlamaTokenizer",
114
+ "unk_token": "<unk>",
115
+ "use_default_system_prompt": false
116
+ }