finalf0 commited on
Commit
17eae37
1 Parent(s): c2b40e6
config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openbmb/CPM-2B",
3
+ "architectures": [
4
+ "MiniCPMForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_minicpm.MiniCPMConfig",
8
+ "AutoModel": "modeling_minicpm.MiniCPMModel",
9
+ "AutoModelForCausalLM": "modeling_minicpm.MiniCPMForCausalLM",
10
+ "AutoModelForSeq2SeqLM": "modeling_minicpm.MiniCPMForCausalLM",
11
+ "AutoModelForSequenceClassification": "modeling_minicpm.MiniCPMForSequenceClassification"
12
+ },
13
+ "bos_token_id": 1,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 2304,
17
+ "initializer_range": 0.1,
18
+ "intermediate_size": 5760,
19
+ "max_position_embeddings": 2048,
20
+ "num_attention_heads": 36,
21
+ "num_hidden_layers": 40,
22
+ "num_key_value_heads": 36,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": null,
25
+ "torch_dtype": "float16",
26
+ "transformers_version": "4.36.0",
27
+ "use_cache": true,
28
+ "vocab_size": 122753,
29
+ "scale_emb": 12,
30
+ "dim_model_base": 256,
31
+ "scale_depth": 1.4,
32
+ "quantization_config": {
33
+ "bits": 4,
34
+ "group_size": 32,
35
+ "damp_percent": 0.01,
36
+ "desc_act": true,
37
+ "sym": false,
38
+ "true_sequential": true,
39
+ "model_name_or_path": null,
40
+ "model_file_base_name": null,
41
+ "quant_method": "gptq",
42
+ "modules_in_block_to_quantize": [
43
+ [
44
+ "self_attn.k_proj",
45
+ "self_attn.v_proj",
46
+ "self_attn.q_proj"
47
+ ],
48
+ [
49
+ "self_attn.o_proj"
50
+ ],
51
+ [
52
+ "mlp.up_proj",
53
+ "mlp.gate_proj"
54
+ ],
55
+ [
56
+ "mlp.down_proj"
57
+ ]
58
+ ]
59
+ }
60
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32000):
40
+ Vocabulary size of the MiniCPM model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`MiniCPMModel`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 11008):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer decoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer decoder.
50
+ num_key_value_heads (`int`, *optional*):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
57
+ `num_attention_heads`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
61
+ The maximum sequence length that this model might ever be used with. MiniCPM 1 supports up to 2048 tokens,
62
+ MiniCPM 2 up to 4096, CodeMiniCPM up to 16384.
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
66
+ The epsilon used by the rms normalization layers.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
69
+ relevant if `config.is_decoder=True`.
70
+ pad_token_id (`int`, *optional*):
71
+ Padding token id.
72
+ bos_token_id (`int`, *optional*, defaults to 1):
73
+ Beginning of stream token id.
74
+ eos_token_id (`int`, *optional*, defaults to 2):
75
+ End of stream token id.
76
+ pretraining_tp (`int`, *optional*, defaults to 1):
77
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
78
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
79
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
80
+ issue](https://github.com/pytorch/pytorch/issues/76232).
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`Dict`, *optional*):
86
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
87
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
88
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
89
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
90
+ these scaling strategies behave:
91
+ https://www.reddit.com/r/LocalMiniCPM/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
92
+ experimental feature, subject to breaking API changes in future versions.
93
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
94
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
95
+ attention_dropout (`float`, *optional*, defaults to 0.0):
96
+ The dropout ratio for the attention probabilities.
97
+ ```python
98
+ >>> from transformers import MiniCPMModel, MiniCPMConfig
99
+ >>> # Initializing a MiniCPM minicpm-7b style configuration
100
+ >>> configuration = MiniCPMConfig()
101
+ >>> # Initializing a model from the minicpm-7b style configuration
102
+ >>> model = MiniCPMModel(configuration)
103
+ >>> # Accessing the model configuration
104
+ >>> configuration = model.config
105
+ ```"""
106
+
107
+ model_type = "minicpm"
108
+ keys_to_ignore_at_inference = ["past_key_values"]
109
+
110
+ def __init__(
111
+ self,
112
+ vocab_size=32000,
113
+ hidden_size=4096,
114
+ intermediate_size=11008,
115
+ num_hidden_layers=32,
116
+ num_attention_heads=32,
117
+ num_key_value_heads=None,
118
+ hidden_act="silu",
119
+ max_position_embeddings=2048,
120
+ initializer_range=0.02,
121
+ rms_norm_eps=1e-6,
122
+ use_cache=True,
123
+ pad_token_id=None,
124
+ bos_token_id=1,
125
+ eos_token_id=2,
126
+ pretraining_tp=1,
127
+ tie_word_embeddings=True,
128
+ rope_theta=10000.0,
129
+ rope_scaling=None,
130
+ attention_bias=False,
131
+ attention_dropout=0.0,
132
+ scale_emb=1,
133
+ dim_model_base=1,
134
+ scale_depth=1,
135
+ **kwargs,
136
+ ):
137
+ self.vocab_size = vocab_size
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.hidden_size = hidden_size
140
+ self.intermediate_size = intermediate_size
141
+ self.num_hidden_layers = num_hidden_layers
142
+ self.num_attention_heads = num_attention_heads
143
+
144
+ # for backward compatibility
145
+ if num_key_value_heads is None:
146
+ num_key_value_heads = num_attention_heads
147
+
148
+ self.num_key_value_heads = num_key_value_heads
149
+ self.hidden_act = hidden_act
150
+ self.initializer_range = initializer_range
151
+ self.rms_norm_eps = rms_norm_eps
152
+ self.pretraining_tp = pretraining_tp
153
+ self.use_cache = use_cache
154
+ self.rope_theta = rope_theta
155
+ self.rope_scaling = rope_scaling
156
+ self._rope_scaling_validation()
157
+ self.attention_bias = attention_bias
158
+ self.attention_dropout = attention_dropout
159
+ self.scale_emb = scale_emb
160
+ self.dim_model_base = dim_model_base
161
+ self.scale_depth = scale_depth
162
+
163
+ super().__init__(
164
+ pad_token_id=pad_token_id,
165
+ bos_token_id=bos_token_id,
166
+ eos_token_id=eos_token_id,
167
+ tie_word_embeddings=tie_word_embeddings,
168
+ **kwargs,
169
+ )
170
+
171
+ def _rope_scaling_validation(self):
172
+ """
173
+ Validate the `rope_scaling` configuration.
174
+ """
175
+ if self.rope_scaling is None:
176
+ return
177
+
178
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
179
+ raise ValueError(
180
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
181
+ f"got {self.rope_scaling}"
182
+ )
183
+ rope_scaling_type = self.rope_scaling.get("type", None)
184
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
185
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
186
+ raise ValueError(
187
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
188
+ )
189
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
190
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
191
+
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample": true,
3
+ "top_p": 0.8,
4
+ "temperature": 0.3,
5
+ "bos_token_id": 1,
6
+ "eos_token_id": 2
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:afb003533e1e425d5eaf13bd80c4ad6c8df7ee4a1b821437dcf5ad1dd3f70852
3
+ size 2548512904
modeling_minicpm.py ADDED
@@ -0,0 +1,1428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_minicpm import MiniCPMConfig
52
+ import re
53
+
54
+
55
+ if is_flash_attn_2_available():
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
58
+
59
+
60
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
61
+ # It means that the function will not be traced through and simply appear as a node in the graph.
62
+ if is_torch_fx_available():
63
+ if not is_torch_greater_or_equal_than_1_13:
64
+ import torch.fx
65
+
66
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
67
+
68
+
69
+ logger = logging.get_logger(__name__)
70
+
71
+ _CONFIG_FOR_DOC = "MiniCPMConfig"
72
+
73
+
74
+ def _get_unpad_data(attention_mask):
75
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
76
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
77
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
78
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
79
+ return (
80
+ indices,
81
+ cu_seqlens,
82
+ max_seqlen_in_batch,
83
+ )
84
+
85
+
86
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
87
+ warnings.warn(
88
+ "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"
89
+ )
90
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
91
+
92
+
93
+ def _make_causal_mask(
94
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
95
+ ):
96
+ warnings.warn(
97
+ "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"
98
+ )
99
+ return AttentionMaskConverter._make_causal_mask(
100
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
101
+ )
102
+
103
+ # @torch.jit.script # type: ignore
104
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
105
+ old_dtype = hidden.dtype
106
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
107
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
108
+ return hidden * weight
109
+
110
+
111
+ class MiniCPMRMSNorm(nn.Module):
112
+ def __init__(self, hidden_size, eps=1e-6):
113
+ """
114
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
115
+ """
116
+ super().__init__()
117
+ self.weight = nn.Parameter(torch.ones(hidden_size))
118
+ self.variance_epsilon = eps
119
+
120
+ def forward(self, hidden_states):
121
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
122
+
123
+
124
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
125
+
126
+
127
+ class MiniCPMRotaryEmbedding(nn.Module):
128
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device="cuda"):
129
+ super().__init__()
130
+
131
+ self.dim = dim
132
+ self.max_position_embeddings = max_position_embeddings
133
+ self.base = base
134
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
135
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
136
+
137
+ # Build here to make `torch.jit.trace` work.
138
+ self._set_cos_sin_cache(
139
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
140
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
141
+ )
142
+
143
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
144
+ self.max_seq_len_cached = seq_len
145
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
146
+ freqs = torch.outer(t, self.inv_freq)
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+
150
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
151
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
152
+
153
+ def forward(self, x, seq_len=None):
154
+ # x: [bs, num_attention_heads, seq_len, head_size]
155
+ if seq_len > self.max_seq_len_cached:
156
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
157
+
158
+ return (
159
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
160
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
161
+ )
162
+
163
+
164
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
165
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
166
+
167
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
168
+ self.scaling_factor = scaling_factor
169
+ super().__init__(dim, max_position_embeddings, base, device)
170
+
171
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
172
+ self.max_seq_len_cached = seq_len
173
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
174
+ t = t / self.scaling_factor
175
+
176
+ freqs = torch.outer(t, self.inv_freq)
177
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
178
+ emb = torch.cat((freqs, freqs), dim=-1)
179
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
180
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
181
+
182
+
183
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
184
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
185
+
186
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
187
+ self.scaling_factor = scaling_factor
188
+ super().__init__(dim, max_position_embeddings, base, device)
189
+
190
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
191
+ self.max_seq_len_cached = seq_len
192
+
193
+ if seq_len > self.max_position_embeddings:
194
+ base = self.base * (
195
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
196
+ ) ** (self.dim / (self.dim - 2))
197
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
198
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
199
+
200
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
201
+
202
+ freqs = torch.outer(t, self.inv_freq)
203
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
204
+ emb = torch.cat((freqs, freqs), dim=-1)
205
+
206
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
207
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
208
+
209
+
210
+ def rotate_half(x):
211
+ """Rotates half the hidden dims of the input."""
212
+ x1 = x[..., : x.shape[-1] // 2]
213
+ x2 = x[..., x.shape[-1] // 2 :]
214
+ return torch.cat((-x2, x1), dim=-1)
215
+
216
+
217
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
218
+ """Applies Rotary Position Embedding to the query and key tensors.
219
+ Args:
220
+ q (`torch.Tensor`): The query tensor.
221
+ k (`torch.Tensor`): The key tensor.
222
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
223
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
224
+ position_ids (`torch.Tensor`):
225
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
226
+ used to pass offsetted position ids when working with a KV-cache.
227
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
228
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
229
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
230
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
231
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
232
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
233
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
234
+ Returns:
235
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
236
+ """
237
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
238
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
239
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
240
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
241
+ orig_dtype = k.dtype
242
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
243
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
244
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
245
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
246
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
247
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
248
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
249
+
250
+ class MiniCPMMLP(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ self.config = config
254
+ self.hidden_size = config.hidden_size
255
+ self.intermediate_size = config.intermediate_size
256
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
257
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
258
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
259
+ self.act_fn = ACT2FN[config.hidden_act]
260
+
261
+ def forward(self, x):
262
+ if self.config.pretraining_tp > 1:
263
+ slice = self.intermediate_size // self.config.pretraining_tp
264
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
265
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
266
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
267
+
268
+ gate_proj = torch.cat(
269
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
270
+ )
271
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
272
+
273
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
274
+ down_proj = [
275
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
276
+ ]
277
+ down_proj = sum(down_proj)
278
+ else:
279
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
280
+
281
+ return down_proj
282
+
283
+
284
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
285
+ """
286
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
287
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
288
+ """
289
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
290
+ if n_rep == 1:
291
+ return hidden_states
292
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
293
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
294
+
295
+
296
+
297
+ class MiniCPMAttention(nn.Module):
298
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
299
+
300
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
301
+ super().__init__()
302
+ self.config = config
303
+ self.layer_idx = layer_idx
304
+ if layer_idx is None:
305
+ logger.warning_once(
306
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
307
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
308
+ "when creating this class."
309
+ )
310
+
311
+ self.attention_dropout = config.attention_dropout
312
+ self.hidden_size = config.hidden_size
313
+ self.num_heads = config.num_attention_heads
314
+ self.head_dim = self.hidden_size // self.num_heads
315
+ self.num_key_value_heads = config.num_key_value_heads
316
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
317
+ self.max_position_embeddings = config.max_position_embeddings
318
+ self.rope_theta = config.rope_theta
319
+ self.is_causal = True
320
+
321
+ if (self.head_dim * self.num_heads) != self.hidden_size:
322
+ raise ValueError(
323
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
324
+ f" and `num_heads`: {self.num_heads})."
325
+ )
326
+
327
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
328
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
329
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
330
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
331
+ self._init_rope()
332
+
333
+ def _init_rope(self):
334
+ if self.config.rope_scaling is None:
335
+ self.rotary_emb = MiniCPMRotaryEmbedding(
336
+ self.head_dim,
337
+ max_position_embeddings=self.max_position_embeddings,
338
+ base=self.rope_theta,
339
+ )
340
+ else:
341
+ scaling_type = self.config.rope_scaling["type"]
342
+ scaling_factor = self.config.rope_scaling["factor"]
343
+ if scaling_type == "linear":
344
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
345
+ self.head_dim,
346
+ max_position_embeddings=self.max_position_embeddings,
347
+ scaling_factor=scaling_factor,
348
+ base=self.rope_theta,
349
+ )
350
+ elif scaling_type == "dynamic":
351
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
352
+ self.head_dim,
353
+ max_position_embeddings=self.max_position_embeddings,
354
+ scaling_factor=scaling_factor,
355
+ base=self.rope_theta,
356
+ )
357
+ else:
358
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
359
+
360
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
361
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
362
+
363
+ def forward(
364
+ self,
365
+ hidden_states: torch.Tensor,
366
+ attention_mask: Optional[torch.Tensor] = None,
367
+ position_ids: Optional[torch.LongTensor] = None,
368
+ past_key_value: Optional[Cache] = None,
369
+ output_attentions: bool = False,
370
+ use_cache: bool = False,
371
+ **kwargs,
372
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
373
+ if "padding_mask" in kwargs:
374
+ warnings.warn(
375
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
376
+ )
377
+
378
+ bsz, q_len, _ = hidden_states.size()
379
+
380
+ if self.config.pretraining_tp > 1:
381
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
382
+ query_slices = self.q_proj.weight.split(
383
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
384
+ )
385
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
386
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
387
+
388
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
389
+ query_states = torch.cat(query_states, dim=-1)
390
+
391
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
392
+ key_states = torch.cat(key_states, dim=-1)
393
+
394
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
395
+ value_states = torch.cat(value_states, dim=-1)
396
+
397
+ else:
398
+ query_states = self.q_proj(hidden_states)
399
+ key_states = self.k_proj(hidden_states)
400
+ value_states = self.v_proj(hidden_states)
401
+
402
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
403
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
404
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
405
+
406
+ kv_seq_len = key_states.shape[-2]
407
+ if past_key_value is not None:
408
+ if self.layer_idx is None:
409
+ raise ValueError(
410
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
411
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
412
+ "with a layer index."
413
+ )
414
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
415
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
416
+
417
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
418
+
419
+ if past_key_value is not None:
420
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
421
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
422
+
423
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
424
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
425
+
426
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
427
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
428
+ raise ValueError(
429
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
430
+ f" {attn_weights.size()}"
431
+ )
432
+
433
+ if attention_mask is not None:
434
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
435
+ raise ValueError(
436
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
437
+ )
438
+ attn_weights = attn_weights + attention_mask
439
+
440
+ # upcast attention to fp32
441
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
442
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
443
+ attn_output = torch.matmul(attn_weights, value_states)
444
+
445
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
446
+ raise ValueError(
447
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
448
+ f" {attn_output.size()}"
449
+ )
450
+
451
+ attn_output = attn_output.transpose(1, 2).contiguous()
452
+
453
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
454
+
455
+ if self.config.pretraining_tp > 1:
456
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
457
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
458
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
459
+ else:
460
+ attn_output = self.o_proj(attn_output)
461
+
462
+ if not output_attentions:
463
+ attn_weights = None
464
+
465
+ return attn_output, attn_weights, past_key_value
466
+
467
+
468
+ class MiniCPMFlashAttention2(MiniCPMAttention):
469
+ """
470
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
471
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
472
+ flash attention and deal with padding tokens in case the input contains any of them.
473
+ """
474
+
475
+ def __init__(self, *args, **kwargs):
476
+ super().__init__(*args, **kwargs)
477
+
478
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
479
+ # 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.
480
+ # 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).
481
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
482
+
483
+ def forward(
484
+ self,
485
+ hidden_states: torch.Tensor,
486
+ attention_mask: Optional[torch.LongTensor] = None,
487
+ position_ids: Optional[torch.LongTensor] = None,
488
+ past_key_value: Optional[Cache] = None,
489
+ output_attentions: bool = False,
490
+ use_cache: bool = False,
491
+ **kwargs,
492
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
493
+ # MiniCPMFlashAttention2 attention does not support output_attentions
494
+ if "padding_mask" in kwargs:
495
+ warnings.warn(
496
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
497
+ )
498
+
499
+ # overwrite attention_mask with padding_mask
500
+ attention_mask = kwargs.pop("padding_mask")
501
+
502
+ output_attentions = False
503
+
504
+ bsz, q_len, _ = hidden_states.size()
505
+
506
+ query_states = self.q_proj(hidden_states)
507
+ key_states = self.k_proj(hidden_states)
508
+ value_states = self.v_proj(hidden_states)
509
+
510
+ # Flash attention requires the input to have the shape
511
+ # batch_size x seq_length x head_dim x hidden_dim
512
+ # therefore we just need to keep the original shape
513
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
514
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
515
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
516
+
517
+ kv_seq_len = key_states.shape[-2]
518
+ if past_key_value is not None:
519
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
520
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
521
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
522
+
523
+ if past_key_value is not None:
524
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
525
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
526
+
527
+ # 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
528
+ # to be able to avoid many of these transpose/reshape/view.
529
+ query_states = query_states.transpose(1, 2)
530
+ key_states = key_states.transpose(1, 2)
531
+ value_states = value_states.transpose(1, 2)
532
+
533
+ dropout_rate = self.attention_dropout if self.training else 0.0
534
+
535
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
536
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
537
+ # cast them back in the correct dtype just to be sure everything works as expected.
538
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
539
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
540
+
541
+ input_dtype = query_states.dtype
542
+ if input_dtype == torch.float32:
543
+ # Handle the case where the model is quantized
544
+ if hasattr(self.config, "_pre_quantization_dtype"):
545
+ target_dtype = self.config._pre_quantization_dtype
546
+ else:
547
+ target_dtype = self.q_proj.weight.dtype
548
+
549
+ logger.warning_once(
550
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
551
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
552
+ f" {target_dtype}."
553
+ )
554
+
555
+ query_states = query_states.to(target_dtype)
556
+ key_states = key_states.to(target_dtype)
557
+ value_states = value_states.to(target_dtype)
558
+
559
+ attn_output = self._flash_attention_forward(
560
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
561
+ )
562
+
563
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
564
+ attn_output = self.o_proj(attn_output)
565
+
566
+ if not output_attentions:
567
+ attn_weights = None
568
+
569
+ return attn_output, attn_weights, past_key_value
570
+
571
+ def _flash_attention_forward(
572
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
573
+ ):
574
+ """
575
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
576
+ first unpad the input, then computes the attention scores and pad the final attention scores.
577
+ Args:
578
+ query_states (`torch.Tensor`):
579
+ Input query states to be passed to Flash Attention API
580
+ key_states (`torch.Tensor`):
581
+ Input key states to be passed to Flash Attention API
582
+ value_states (`torch.Tensor`):
583
+ Input value states to be passed to Flash Attention API
584
+ attention_mask (`torch.Tensor`):
585
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
586
+ position of padding tokens and 1 for the position of non-padding tokens.
587
+ dropout (`int`, *optional*):
588
+ Attention dropout
589
+ softmax_scale (`float`, *optional*):
590
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
591
+ """
592
+ if not self._flash_attn_uses_top_left_mask:
593
+ causal = self.is_causal
594
+ else:
595
+ # 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__.
596
+ causal = self.is_causal and query_length != 1
597
+ # Contains at least one padding token in the sequence
598
+ if attention_mask is not None:
599
+ batch_size = query_states.shape[0]
600
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
601
+ query_states, key_states, value_states, attention_mask, query_length
602
+ )
603
+
604
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
605
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
606
+ attn_output_unpad = flash_attn_varlen_func(
607
+ query_states,
608
+ key_states,
609
+ value_states,
610
+ cu_seqlens_q=cu_seqlens_q,
611
+ cu_seqlens_k=cu_seqlens_k,
612
+ max_seqlen_q=max_seqlen_in_batch_q,
613
+ max_seqlen_k=max_seqlen_in_batch_k,
614
+ dropout_p=dropout,
615
+ softmax_scale=softmax_scale,
616
+ causal=causal,
617
+ )
618
+
619
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
620
+ else:
621
+ attn_output = flash_attn_func(
622
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
623
+ )
624
+
625
+ return attn_output
626
+
627
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
628
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
629
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
630
+
631
+ key_layer = index_first_axis(
632
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
633
+ )
634
+ value_layer = index_first_axis(
635
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
636
+ )
637
+ if query_length == kv_seq_len:
638
+ query_layer = index_first_axis(
639
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
640
+ )
641
+ cu_seqlens_q = cu_seqlens_k
642
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
643
+ indices_q = indices_k
644
+ elif query_length == 1:
645
+ max_seqlen_in_batch_q = 1
646
+ cu_seqlens_q = torch.arange(
647
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
648
+ ) # There is a memcpy here, that is very bad.
649
+ indices_q = cu_seqlens_q[:-1]
650
+ query_layer = query_layer.squeeze(1)
651
+ else:
652
+ # The -q_len: slice assumes left padding.
653
+ attention_mask = attention_mask[:, -query_length:]
654
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
655
+
656
+ return (
657
+ query_layer,
658
+ key_layer,
659
+ value_layer,
660
+ indices_q,
661
+ (cu_seqlens_q, cu_seqlens_k),
662
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
663
+ )
664
+
665
+
666
+ class MiniCPMSdpaAttention(MiniCPMAttention):
667
+ """
668
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
669
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
670
+ SDPA API.
671
+ """
672
+
673
+ # Adapted from MiniCPMAttention.forward
674
+ def forward(
675
+ self,
676
+ hidden_states: torch.Tensor,
677
+ attention_mask: Optional[torch.Tensor] = None,
678
+ position_ids: Optional[torch.LongTensor] = None,
679
+ past_key_value: Optional[Cache] = None,
680
+ output_attentions: bool = False,
681
+ use_cache: bool = False,
682
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
683
+ if output_attentions:
684
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
685
+ logger.warning_once(
686
+ "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, "
687
+ '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.'
688
+ )
689
+ return super().forward(
690
+ hidden_states=hidden_states,
691
+ attention_mask=attention_mask,
692
+ position_ids=position_ids,
693
+ past_key_value=past_key_value,
694
+ output_attentions=output_attentions,
695
+ use_cache=use_cache,
696
+ )
697
+
698
+ bsz, q_len, _ = hidden_states.size()
699
+
700
+ query_states = self.q_proj(hidden_states)
701
+ key_states = self.k_proj(hidden_states)
702
+ value_states = self.v_proj(hidden_states)
703
+
704
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
705
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
706
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
707
+
708
+ kv_seq_len = key_states.shape[-2]
709
+ if past_key_value is not None:
710
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
711
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
712
+
713
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
714
+
715
+ if past_key_value is not None:
716
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
717
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
718
+
719
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
720
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
721
+
722
+ if attention_mask is not None:
723
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
724
+ raise ValueError(
725
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
726
+ )
727
+
728
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
729
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
730
+ if query_states.device.type == "cuda" and attention_mask is not None:
731
+ query_states = query_states.contiguous()
732
+ key_states = key_states.contiguous()
733
+ value_states = value_states.contiguous()
734
+
735
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
736
+ query_states,
737
+ key_states,
738
+ value_states,
739
+ attn_mask=attention_mask,
740
+ dropout_p=self.attention_dropout if self.training else 0.0,
741
+ # 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.
742
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
743
+ )
744
+
745
+ attn_output = attn_output.transpose(1, 2).contiguous()
746
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
747
+
748
+ attn_output = self.o_proj(attn_output)
749
+
750
+ return attn_output, None, past_key_value
751
+
752
+
753
+ MINICPM_ATTENTION_CLASSES = {
754
+ "eager": MiniCPMAttention,
755
+ "flash_attention_2": MiniCPMFlashAttention2,
756
+ "sdpa": MiniCPMSdpaAttention,
757
+ }
758
+
759
+
760
+ class MiniCPMDecoderLayer(nn.Module):
761
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
762
+ super().__init__()
763
+ self.hidden_size = config.hidden_size
764
+
765
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
766
+
767
+ self.mlp = MiniCPMMLP(config)
768
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
769
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
770
+
771
+ self.scale_depth = config.scale_depth
772
+ self.num_hidden_layers = config.num_hidden_layers
773
+
774
+ def forward(
775
+ self,
776
+ hidden_states: torch.Tensor,
777
+ attention_mask: Optional[torch.Tensor] = None,
778
+ position_ids: Optional[torch.LongTensor] = None,
779
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
780
+ output_attentions: Optional[bool] = False,
781
+ use_cache: Optional[bool] = False,
782
+ **kwargs,
783
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
784
+ """
785
+ Args:
786
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
787
+ attention_mask (`torch.FloatTensor`, *optional*):
788
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
789
+ query_sequence_length, key_sequence_length)` if default attention is used.
790
+ output_attentions (`bool`, *optional*):
791
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
792
+ returned tensors for more detail.
793
+ use_cache (`bool`, *optional*):
794
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
795
+ (see `past_key_values`).
796
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
797
+ """
798
+ if "padding_mask" in kwargs:
799
+ warnings.warn(
800
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
801
+ )
802
+
803
+ residual = hidden_states
804
+ hidden_states = self.input_layernorm(hidden_states)
805
+ # Self Attention
806
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
807
+ hidden_states=hidden_states,
808
+ attention_mask=attention_mask,
809
+ position_ids=position_ids,
810
+ past_key_value=past_key_value,
811
+ output_attentions=output_attentions,
812
+ use_cache=use_cache,
813
+ **kwargs,
814
+ )
815
+
816
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
817
+
818
+ # Fully Connected
819
+ residual = hidden_states
820
+ hidden_states = self.post_attention_layernorm(hidden_states)
821
+
822
+ hidden_states = self.mlp(hidden_states)
823
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
824
+
825
+ outputs = (hidden_states,)
826
+
827
+ if output_attentions:
828
+ outputs += (self_attn_weights,)
829
+
830
+ if use_cache:
831
+ outputs += (present_key_value,)
832
+
833
+ return outputs
834
+
835
+
836
+ MINICPM_START_DOCSTRING = r"""
837
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
838
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
839
+ etc.)
840
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
841
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
842
+ and behavior.
843
+ Parameters:
844
+ config ([`MiniCPMConfig`]):
845
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
846
+ load the weights associated with the model, only the configuration. Check out the
847
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
848
+ """
849
+
850
+
851
+ @add_start_docstrings(
852
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
853
+ MINICPM_START_DOCSTRING,
854
+ )
855
+ class MiniCPMPreTrainedModel(PreTrainedModel):
856
+ config_class = MiniCPMConfig
857
+ base_model_prefix = "model"
858
+ supports_gradient_checkpointing = True
859
+ _no_split_modules = ["MiniCPMDecoderLayer"]
860
+ _skip_keys_device_placement = "past_key_values"
861
+ _supports_flash_attn_2 = True
862
+ _supports_sdpa = True
863
+ _supports_cache_class = True
864
+
865
+ def _init_weights(self, module):
866
+ std = self.config.initializer_range
867
+ if isinstance(module, nn.Linear):
868
+ module.weight.data.normal_(mean=0.0, std=std)
869
+ if module.bias is not None:
870
+ module.bias.data.zero_()
871
+ elif isinstance(module, nn.Embedding):
872
+ module.weight.data.normal_(mean=0.0, std=std)
873
+ if module.padding_idx is not None:
874
+ module.weight.data[module.padding_idx].zero_()
875
+
876
+
877
+ MINICPM_INPUTS_DOCSTRING = r"""
878
+ Args:
879
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
880
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
881
+ it.
882
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
883
+ [`PreTrainedTokenizer.__call__`] for details.
884
+ [What are input IDs?](../glossary#input-ids)
885
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
886
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
887
+ - 1 for tokens that are **not masked**,
888
+ - 0 for tokens that are **masked**.
889
+ [What are attention masks?](../glossary#attention-mask)
890
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
891
+ [`PreTrainedTokenizer.__call__`] for details.
892
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
893
+ `past_key_values`).
894
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
895
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
896
+ information on the default strategy.
897
+ - 1 indicates the head is **not masked**,
898
+ - 0 indicates the head is **masked**.
899
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
900
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
901
+ config.n_positions - 1]`.
902
+ [What are position IDs?](../glossary#position-ids)
903
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
904
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
905
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
906
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
907
+ Two formats are allowed:
908
+ - a [`~cache_utils.Cache`] instance;
909
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
910
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
911
+ cache format.
912
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
913
+ legacy cache format will be returned.
914
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
915
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
916
+ of shape `(batch_size, sequence_length)`.
917
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
918
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
919
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
920
+ model's internal embedding lookup matrix.
921
+ use_cache (`bool`, *optional*):
922
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
923
+ `past_key_values`).
924
+ output_attentions (`bool`, *optional*):
925
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
926
+ tensors for more detail.
927
+ output_hidden_states (`bool`, *optional*):
928
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
929
+ more detail.
930
+ return_dict (`bool`, *optional*):
931
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
932
+ """
933
+
934
+
935
+ @add_start_docstrings(
936
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
937
+ MINICPM_START_DOCSTRING,
938
+ )
939
+ class MiniCPMModel(MiniCPMPreTrainedModel):
940
+ """
941
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
942
+ Args:
943
+ config: MiniCPMConfig
944
+ """
945
+
946
+ def __init__(self, config: MiniCPMConfig):
947
+ super().__init__(config)
948
+ self.padding_idx = config.pad_token_id
949
+ self.vocab_size = config.vocab_size
950
+
951
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
952
+ self.layers = nn.ModuleList(
953
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
954
+ )
955
+ self._use_sdpa = config._attn_implementation == "sdpa"
956
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
957
+
958
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
959
+
960
+ self.gradient_checkpointing = False
961
+ # Initialize weights and apply final processing
962
+ self.post_init()
963
+
964
+ def get_input_embeddings(self):
965
+ return self.embed_tokens
966
+
967
+ def set_input_embeddings(self, value):
968
+ self.embed_tokens = value
969
+
970
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
971
+ def forward(
972
+ self,
973
+ input_ids: torch.LongTensor = None,
974
+ attention_mask: Optional[torch.Tensor] = None,
975
+ position_ids: Optional[torch.LongTensor] = None,
976
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
977
+ inputs_embeds: Optional[torch.FloatTensor] = None,
978
+ use_cache: Optional[bool] = None,
979
+ output_attentions: Optional[bool] = None,
980
+ output_hidden_states: Optional[bool] = None,
981
+ return_dict: Optional[bool] = None,
982
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
983
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
984
+ output_hidden_states = (
985
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
986
+ )
987
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
988
+
989
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
990
+
991
+ # retrieve input_ids and inputs_embeds
992
+ if input_ids is not None and inputs_embeds is not None:
993
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
994
+ elif input_ids is not None:
995
+ batch_size, seq_length = input_ids.shape[:2]
996
+ elif inputs_embeds is not None:
997
+ batch_size, seq_length = inputs_embeds.shape[:2]
998
+ else:
999
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1000
+
1001
+ if self.gradient_checkpointing and self.training:
1002
+ if use_cache:
1003
+ logger.warning_once(
1004
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1005
+ )
1006
+ use_cache = False
1007
+
1008
+ past_key_values_length = 0
1009
+ if use_cache:
1010
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1011
+ if use_legacy_cache:
1012
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1013
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1014
+
1015
+ if position_ids is None:
1016
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1017
+ position_ids = torch.arange(
1018
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1019
+ )
1020
+ position_ids = position_ids.unsqueeze(0)
1021
+
1022
+ if inputs_embeds is None:
1023
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1024
+
1025
+ if self._use_flash_attention_2:
1026
+ # 2d mask is passed through the layers
1027
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1028
+ elif self._use_sdpa and not output_attentions:
1029
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1030
+ # the manual implementation that requires a 4D causal mask in all cases.
1031
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1032
+ attention_mask,
1033
+ (batch_size, seq_length),
1034
+ inputs_embeds,
1035
+ past_key_values_length,
1036
+ )
1037
+ else:
1038
+ # 4d mask is passed through the layers
1039
+ attention_mask = _prepare_4d_causal_attention_mask(
1040
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1041
+ )
1042
+
1043
+ # embed positions
1044
+ hidden_states = inputs_embeds
1045
+
1046
+ # decoder layers
1047
+ all_hidden_states = () if output_hidden_states else None
1048
+ all_self_attns = () if output_attentions else None
1049
+ next_decoder_cache = None
1050
+
1051
+ for decoder_layer in self.layers:
1052
+ if output_hidden_states:
1053
+ all_hidden_states += (hidden_states,)
1054
+
1055
+ if self.gradient_checkpointing and self.training:
1056
+ layer_outputs = self._gradient_checkpointing_func(
1057
+ decoder_layer.__call__,
1058
+ hidden_states,
1059
+ attention_mask,
1060
+ position_ids,
1061
+ past_key_values,
1062
+ output_attentions,
1063
+ use_cache,
1064
+ )
1065
+ else:
1066
+ layer_outputs = decoder_layer(
1067
+ hidden_states,
1068
+ attention_mask=attention_mask,
1069
+ position_ids=position_ids,
1070
+ past_key_value=past_key_values,
1071
+ output_attentions=output_attentions,
1072
+ use_cache=use_cache,
1073
+ )
1074
+
1075
+ hidden_states = layer_outputs[0]
1076
+
1077
+ if use_cache:
1078
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1079
+
1080
+ if output_attentions:
1081
+ all_self_attns += (layer_outputs[1],)
1082
+
1083
+ hidden_states = self.norm(hidden_states)
1084
+
1085
+ # add hidden states from the last decoder layer
1086
+ if output_hidden_states:
1087
+ all_hidden_states += (hidden_states,)
1088
+
1089
+ next_cache = None
1090
+ if use_cache:
1091
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1092
+ if not return_dict:
1093
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1094
+ return BaseModelOutputWithPast(
1095
+ last_hidden_state=hidden_states,
1096
+ past_key_values=next_cache,
1097
+ hidden_states=all_hidden_states,
1098
+ attentions=all_self_attns,
1099
+ )
1100
+
1101
+
1102
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1103
+ _tied_weights_keys = ["lm_head.weight"]
1104
+
1105
+ def __init__(self, config):
1106
+ super().__init__(config)
1107
+ self.model = MiniCPMModel(config)
1108
+ self.vocab_size = config.vocab_size
1109
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1110
+
1111
+ # Initialize weights and apply final processing
1112
+ self.post_init()
1113
+
1114
+ def get_input_embeddings(self):
1115
+ return self.model.embed_tokens
1116
+
1117
+ def set_input_embeddings(self, value):
1118
+ self.model.embed_tokens = value
1119
+
1120
+ def get_output_embeddings(self):
1121
+ return self.lm_head
1122
+
1123
+ def set_output_embeddings(self, new_embeddings):
1124
+ self.lm_head = new_embeddings
1125
+
1126
+ def set_decoder(self, decoder):
1127
+ self.model = decoder
1128
+
1129
+ def get_decoder(self):
1130
+ return self.model
1131
+
1132
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1133
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1134
+ def forward(
1135
+ self,
1136
+ input_ids: torch.LongTensor = None,
1137
+ attention_mask: Optional[torch.Tensor] = None,
1138
+ position_ids: Optional[torch.LongTensor] = None,
1139
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1140
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1141
+ labels: Optional[torch.LongTensor] = None,
1142
+ use_cache: Optional[bool] = None,
1143
+ output_attentions: Optional[bool] = None,
1144
+ output_hidden_states: Optional[bool] = None,
1145
+ return_dict: Optional[bool] = None,
1146
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1147
+ r"""
1148
+ Args:
1149
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1150
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1151
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1152
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1153
+ Returns:
1154
+ Example:
1155
+ ```python
1156
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1157
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1158
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1159
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1160
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1161
+ >>> # Generate
1162
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1163
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1164
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1165
+ ```"""
1166
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1167
+ output_hidden_states = (
1168
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1169
+ )
1170
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1171
+
1172
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1173
+ outputs = self.model(
1174
+ input_ids=input_ids,
1175
+ attention_mask=attention_mask,
1176
+ position_ids=position_ids,
1177
+ past_key_values=past_key_values,
1178
+ inputs_embeds=inputs_embeds,
1179
+ use_cache=use_cache,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ )
1184
+
1185
+ hidden_states = outputs[0]
1186
+ if self.config.pretraining_tp > 1:
1187
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1188
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1189
+ logits = torch.cat(logits, dim=-1)
1190
+ else:
1191
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1192
+ logits = logits.float()
1193
+
1194
+ loss = None
1195
+ if labels is not None:
1196
+ # Shift so that tokens < n predict n
1197
+ shift_logits = logits[..., :-1, :].contiguous()
1198
+ shift_labels = labels[..., 1:].contiguous()
1199
+ # Flatten the tokens
1200
+ loss_fct = CrossEntropyLoss()
1201
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1202
+ shift_labels = shift_labels.view(-1)
1203
+ # Enable model parallelism
1204
+ shift_labels = shift_labels.to(shift_logits.device)
1205
+ loss = loss_fct(shift_logits, shift_labels)
1206
+
1207
+ if not return_dict:
1208
+ output = (logits,) + outputs[1:]
1209
+ return (loss,) + output if loss is not None else output
1210
+
1211
+ return CausalLMOutputWithPast(
1212
+ loss=loss,
1213
+ logits=logits,
1214
+ past_key_values=outputs.past_key_values,
1215
+ hidden_states=outputs.hidden_states,
1216
+ attentions=outputs.attentions,
1217
+ )
1218
+
1219
+ def prepare_inputs_for_generation(
1220
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1221
+ ):
1222
+ if past_key_values is not None:
1223
+ if isinstance(past_key_values, Cache):
1224
+ cache_length = past_key_values.get_seq_length()
1225
+ past_length = past_key_values.seen_tokens
1226
+ max_cache_length = past_key_values.get_max_length()
1227
+ else:
1228
+ cache_length = past_length = past_key_values[0][0].shape[2]
1229
+ max_cache_length = None
1230
+
1231
+ # Keep only the unprocessed tokens:
1232
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1233
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1234
+ # input)
1235
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1236
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1237
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1238
+ # input_ids based on the past_length.
1239
+ elif past_length < input_ids.shape[1]:
1240
+ input_ids = input_ids[:, past_length:]
1241
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1242
+
1243
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1244
+ if (
1245
+ max_cache_length is not None
1246
+ and attention_mask is not None
1247
+ and cache_length + input_ids.shape[1] > max_cache_length
1248
+ ):
1249
+ attention_mask = attention_mask[:, -max_cache_length:]
1250
+
1251
+ position_ids = kwargs.get("position_ids", None)
1252
+ if attention_mask is not None and position_ids is None:
1253
+ # create position_ids on the fly for batch generation
1254
+ position_ids = attention_mask.long().cumsum(-1) - 1
1255
+ position_ids.masked_fill_(attention_mask == 0, 1)
1256
+ if past_key_values:
1257
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1258
+
1259
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1260
+ if inputs_embeds is not None and past_key_values is None:
1261
+ model_inputs = {"inputs_embeds": inputs_embeds}
1262
+ else:
1263
+ model_inputs = {"input_ids": input_ids}
1264
+
1265
+ model_inputs.update(
1266
+ {
1267
+ "position_ids": position_ids,
1268
+ "past_key_values": past_key_values,
1269
+ "use_cache": kwargs.get("use_cache"),
1270
+ "attention_mask": attention_mask,
1271
+ }
1272
+ )
1273
+ return model_inputs
1274
+
1275
+ @staticmethod
1276
+ def _reorder_cache(past_key_values, beam_idx):
1277
+ reordered_past = ()
1278
+ for layer_past in past_key_values:
1279
+ reordered_past += (
1280
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1281
+ )
1282
+ return reordered_past
1283
+
1284
+ @torch.inference_mode()
1285
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
1286
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1287
+ **kwargs):
1288
+ if history is None:
1289
+ history = []
1290
+ if logits_processor:
1291
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1292
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1293
+ else:
1294
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1295
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1296
+
1297
+ history.append({"role": role, "content": query})
1298
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1299
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1300
+ outputs = self.generate(**inputs, **gen_kwargs)
1301
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1302
+ response = tokenizer.decode(outputs)
1303
+ pattern = re.compile(r".*?(?=<AI>|<用户>)", re.DOTALL)
1304
+ matches = pattern.findall(response)
1305
+ if len(matches) > 0:
1306
+ response = matches[0]
1307
+ history.append({"role": "assistant", "content": response})
1308
+ return response, history
1309
+
1310
+
1311
+ @add_start_docstrings(
1312
+ """
1313
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1314
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1315
+ (e.g. GPT-2) do.
1316
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1317
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1318
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1319
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1320
+ each row of the batch).
1321
+ """,
1322
+ MINICPM_START_DOCSTRING,
1323
+ )
1324
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1325
+ def __init__(self, config):
1326
+ super().__init__(config)
1327
+ self.num_labels = config.num_labels
1328
+ self.model = MiniCPMModel(config)
1329
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1330
+
1331
+ # Initialize weights and apply final processing
1332
+ self.post_init()
1333
+
1334
+ def get_input_embeddings(self):
1335
+ return self.model.embed_tokens
1336
+
1337
+ def set_input_embeddings(self, value):
1338
+ self.model.embed_tokens = value
1339
+
1340
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1341
+ def forward(
1342
+ self,
1343
+ input_ids: torch.LongTensor = None,
1344
+ attention_mask: Optional[torch.Tensor] = None,
1345
+ position_ids: Optional[torch.LongTensor] = None,
1346
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1347
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1348
+ labels: Optional[torch.LongTensor] = None,
1349
+ use_cache: Optional[bool] = None,
1350
+ output_attentions: Optional[bool] = None,
1351
+ output_hidden_states: Optional[bool] = None,
1352
+ return_dict: Optional[bool] = None,
1353
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1354
+ r"""
1355
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1356
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1357
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1358
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1359
+ """
1360
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1361
+
1362
+ transformer_outputs = self.model(
1363
+ input_ids,
1364
+ attention_mask=attention_mask,
1365
+ position_ids=position_ids,
1366
+ past_key_values=past_key_values,
1367
+ inputs_embeds=inputs_embeds,
1368
+ use_cache=use_cache,
1369
+ output_attentions=output_attentions,
1370
+ output_hidden_states=output_hidden_states,
1371
+ return_dict=return_dict,
1372
+ )
1373
+ hidden_states = transformer_outputs[0]
1374
+ logits = self.score(hidden_states)
1375
+
1376
+ if input_ids is not None:
1377
+ batch_size = input_ids.shape[0]
1378
+ else:
1379
+ batch_size = inputs_embeds.shape[0]
1380
+
1381
+ if self.config.pad_token_id is None and batch_size != 1:
1382
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1383
+ if self.config.pad_token_id is None:
1384
+ sequence_lengths = -1
1385
+ else:
1386
+ if input_ids is not None:
1387
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1388
+ logits.device
1389
+ )
1390
+ else:
1391
+ sequence_lengths = -1
1392
+
1393
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1394
+
1395
+ loss = None
1396
+ if labels is not None:
1397
+ labels = labels.to(logits.device)
1398
+ if self.config.problem_type is None:
1399
+ if self.num_labels == 1:
1400
+ self.config.problem_type = "regression"
1401
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1402
+ self.config.problem_type = "single_label_classification"
1403
+ else:
1404
+ self.config.problem_type = "multi_label_classification"
1405
+
1406
+ if self.config.problem_type == "regression":
1407
+ loss_fct = MSELoss()
1408
+ if self.num_labels == 1:
1409
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1410
+ else:
1411
+ loss = loss_fct(pooled_logits, labels)
1412
+ elif self.config.problem_type == "single_label_classification":
1413
+ loss_fct = CrossEntropyLoss()
1414
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1415
+ elif self.config.problem_type == "multi_label_classification":
1416
+ loss_fct = BCEWithLogitsLoss()
1417
+ loss = loss_fct(pooled_logits, labels)
1418
+ if not return_dict:
1419
+ output = (pooled_logits,) + transformer_outputs[1:]
1420
+ return ((loss,) + output) if loss is not None else output
1421
+
1422
+ return SequenceClassifierOutputWithPast(
1423
+ loss=loss,
1424
+ logits=pooled_logits,
1425
+ past_key_values=transformer_outputs.past_key_values,
1426
+ hidden_states=transformer_outputs.hidden_states,
1427
+ attentions=transformer_outputs.attentions,
1428
+ )
quantize_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bits": 4,
3
+ "group_size": 32,
4
+ "damp_percent": 0.01,
5
+ "desc_act": false,
6
+ "static_groups": false,
7
+ "sym": false,
8
+ "true_sequential": true,
9
+ "model_name_or_path": "openbmb/MiniCPM-2B-sft-int4",
10
+ "model_file_base_name": "gptq_model-4bit-32g"
11
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
24
+
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9aafcd7da1f5611dab6be545db74d5552a2ccc9c2a12c72ea7be63aac4a25d7
3
+ size 1994871
tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
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
+ },
30
+ "bos_token": "<s>",
31
+ "clean_up_tokenization_spaces": false,
32
+ "eos_token": "</s>",
33
+ "legacy": true,
34
+ "model_max_length": 1000000000000000019884624838656,
35
+ "pad_token": null,
36
+ "sp_model_kwargs": {},
37
+ "spaces_between_special_tokens": false,
38
+ "tokenizer_class": "LlamaTokenizer",
39
+ "unk_token": "<unk>",
40
+ "use_default_system_prompt": false,
41
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'user' %}{{'<用户>' + message['content'].strip() + '<AI>'}}{% else %}{{message['content'].strip()}}{% endif %}{% endfor %}"
42
+ }
43
+