MeowFET commited on
Commit
59bcea7
·
1 Parent(s): dfa67e8

init: add model checkpoint

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