ArchiveStudio BigDong commited on
Commit
71eb740
·
0 Parent(s):

Duplicate from openbmb/MiniCPM4-0.5B

Browse files

Co-authored-by: Yudong Wang <BigDong@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - zh
5
+ - en
6
+ pipeline_tag: text-generation
7
+ library_name: transformers
8
+ ---
9
+ <div align="center">
10
+ <img src="https://github.com/OpenBMB/MiniCPM/blob/main/assets/minicpm_logo.png?raw=true" width="500em" ></img>
11
+ </div>
12
+
13
+ <p align="center">
14
+ <a href="https://github.com/OpenBMB/MiniCPM/" target="_blank">GitHub Repo</a> |
15
+ <a href="https://github.com/OpenBMB/MiniCPM/tree/main/report/MiniCPM_4_Technical_Report.pdf" target="_blank">Technical Report</a>
16
+ </p>
17
+ <p align="center">
18
+ 👋 Join us on <a href="https://discord.gg/3cGQn9b3YM" target="_blank">Discord</a> and <a href="https://github.com/OpenBMB/MiniCPM/blob/main/assets/wechat.jpg" target="_blank">WeChat</a>
19
+ </p>
20
+
21
+ ## What's New
22
+ - [2025.06.06] **MiniCPM4** series are released! This model achieves ultimate efficiency improvements while maintaining optimal performance at the same scale! It can achieve over 5x generation acceleration on typical end-side chips! You can find technical report [here](https://github.com/OpenBMB/MiniCPM/tree/main/report/MiniCPM_4_Technical_Report.pdf).🔥🔥🔥
23
+
24
+ ## MiniCPM4 Series
25
+ MiniCPM4 series are highly efficient large language models (LLMs) designed explicitly for end-side devices, which achieves this efficiency through systematic innovation in four key dimensions: model architecture, training data, training algorithms, and inference systems.
26
+ - [MiniCPM4-8B](https://huggingface.co/openbmb/MiniCPM4-8B): The flagship of MiniCPM4, with 8B parameters, trained on 8T tokens.
27
+ - [MiniCPM4-0.5B](https://huggingface.co/openbmb/MiniCPM4-0.5B): The small version of MiniCPM4, with 0.5B parameters, trained on 1T tokens. (**<-- you are here**)
28
+ - [MiniCPM4-8B-Eagle-FRSpec](https://huggingface.co/openbmb/MiniCPM4-8B-Eagle-FRSpec): Eagle head for FRSpec, accelerating speculative inference for MiniCPM4-8B.
29
+ - [MiniCPM4-8B-Eagle-FRSpec-QAT-cpmcu](https://huggingface.co/openbmb/MiniCPM4-8B-Eagle-FRSpec-QAT-cpmcu): Eagle head trained with QAT for FRSpec, efficiently integrate speculation and quantization to achieve ultra acceleration for MiniCPM4-8B.
30
+ - [MiniCPM4-8B-Eagle-vLLM](https://huggingface.co/openbmb/MiniCPM4-8B-Eagle-vLLM): Eagle head in vLLM format, accelerating speculative inference for MiniCPM4-8B.
31
+ - [MiniCPM4-8B-marlin-Eagle-vLLM](https://huggingface.co/openbmb/MiniCPM4-8B-marlin-Eagle-vLLM): Quantized Eagle head for vLLM format, accelerating speculative inference for MiniCPM4-8B.
32
+ - [BitCPM4-0.5B](https://huggingface.co/openbmb/BitCPM4-0.5B): Extreme ternary quantization applied to MiniCPM4-0.5B compresses model parameters into ternary values, achieving a 90% reduction in bit width.
33
+ - [BitCPM4-1B](https://huggingface.co/openbmb/BitCPM4-1B): Extreme ternary quantization applied to MiniCPM3-1B compresses model parameters into ternary values, achieving a 90% reduction in bit width.
34
+ - [MiniCPM4-Survey](https://huggingface.co/openbmb/MiniCPM4-Survey): Based on MiniCPM4-8B, accepts users' quiries as input and autonomously generate trustworthy, long-form survey papers.
35
+ - [MiniCPM4-MCP](https://huggingface.co/openbmb/MiniCPM4-MCP): Based on MiniCPM4-8B, accepts users' queries and available MCP tools as input and autonomously calls relevant MCP tools to satisfy users' requirements.
36
+
37
+ ## Introduction
38
+ MiniCPM 4 is an extremely efficient edge-side large model that has undergone efficient optimization across four dimensions: model architecture, learning algorithms, training data, and inference systems, achieving ultimate efficiency improvements.
39
+
40
+ - 🏗️ **Efficient Model Architecture:**
41
+ - InfLLM v2 -- Trainable Sparse Attention Mechanism: Adopts a trainable sparse attention mechanism architecture where each token only needs to compute relevance with less than 5% of tokens in 128K long text processing, significantly reducing computational overhead for long texts
42
+
43
+ - 🧠 **Efficient Learning Algorithms:**
44
+ - Model Wind Tunnel 2.0 -- Efficient Predictable Scaling: Introduces scaling prediction methods for performance of downstream tasks, enabling more precise model training configuration search
45
+ - BitCPM -- Ultimate Ternary Quantization: Compresses model parameter bit-width to 3 values, achieving 90% extreme model bit-width reduction
46
+ - Efficient Training Engineering Optimization: Adopts FP8 low-precision computing technology combined with Multi-token Prediction training strategy
47
+
48
+ - 📚 **High-Quality Training Data:**
49
+ - UltraClean -- High-quality Pre-training Data Filtering and Generation: Builds iterative data cleaning strategies based on efficient data verification, open-sourcing high-quality Chinese and English pre-training dataset [UltraFinweb](https://huggingface.co/datasets/openbmb/Ultra-FineWeb)
50
+ - UltraChat v2 -- High-quality Supervised Fine-tuning Data Generation: Constructs large-scale high-quality supervised fine-tuning datasets covering multiple dimensions including knowledge-intensive data, reasoning-intensive data, instruction-following data, long text understanding data, and tool calling data
51
+
52
+ - ⚡ **Efficient Inference System:**
53
+ - CPM.cu -- Lightweight and Efficient CUDA Inference Framework: Integrates sparse attention, model quantization, and speculative sampling to achieve efficient prefilling and decoding
54
+ - ArkInfer -- Cross-platform Deployment System: Supports efficient deployment across multiple backend environments, providing flexible cross-platform adaptation capabilities
55
+
56
+ ## Usage
57
+ ### Inference with Transformers
58
+ ```python
59
+ from transformers import AutoModelForCausalLM, AutoTokenizer
60
+ import torch
61
+ torch.manual_seed(0)
62
+
63
+ path = 'openbmb/MiniCPM4-0.5B'
64
+ device = "cuda"
65
+ tokenizer = AutoTokenizer.from_pretrained(path)
66
+ model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16, device_map=device, trust_remote_code=True)
67
+
68
+ # User can directly use the chat interface
69
+ responds, history = model.chat(tokenizer, "Write an article about Artificial Intelligence.", temperature=0.7, top_p=0.7)
70
+ print(responds)
71
+
72
+ # User can also use the generate interface
73
+ # messages = [
74
+ # {"role": "user", "content": "Write an article about Artificial Intelligence."},
75
+ # ]
76
+ # prompt_text = tokenizer.apply_chat_template(
77
+ # messages,
78
+ # tokenize=False,
79
+ # add_generation_prompt=True,
80
+ # )
81
+ # model_inputs = tokenizer([prompt_text], return_tensors="pt").to(device)
82
+
83
+ # model_outputs = model.generate(
84
+ # **model_inputs,
85
+ # max_new_tokens=1024,
86
+ # top_p=0.7,
87
+ # temperature=0.7
88
+ # )
89
+ # output_token_ids = [
90
+ # model_outputs[i][len(model_inputs[i]):] for i in range(len(model_inputs['input_ids']))
91
+ # ]
92
+
93
+ # responses = tokenizer.batch_decode(output_token_ids, skip_special_tokens=True)[0]
94
+ # print(responses)
95
+ ```
96
+
97
+ ### Inference with [SGLang](https://github.com/sgl-project/sglang)
98
+
99
+ For now, you need to install our forked version of SGLang.
100
+ ```bash
101
+ git clone -b openbmb https://github.com/OpenBMB/sglang.git
102
+ cd sglang
103
+
104
+ pip install --upgrade pip
105
+ pip install -e "python[all]"
106
+ ```
107
+
108
+ You can start the inference server by running the following command:
109
+ ```bash
110
+ python -m sglang.launch_server --model openbmb/MiniCPM4-0.5B --trust-remote-code --port 30000 --chat-template chatml
111
+ ```
112
+
113
+ Then you can use the chat interface by running the following command:
114
+ ```python
115
+ import openai
116
+
117
+ client = openai.Client(base_url=f"http://localhost:30000/v1", api_key="None")
118
+
119
+ response = client.chat.completions.create(
120
+ model="openbmb/MiniCPM4-0.5B",
121
+ messages=[
122
+ {"role": "user", "content": "Write an article about Artificial Intelligence."},
123
+ ],
124
+ temperature=0.7,
125
+ max_tokens=1024,
126
+ )
127
+
128
+ print(response.choices[0].message.content)
129
+ ```
130
+
131
+ ### Inference with [vLLM](https://github.com/vllm-project/vllm)
132
+ For now, you need to install the latest version of vLLM.
133
+ ```
134
+ pip install -U vllm \
135
+ --pre \
136
+ --extra-index-url https://wheels.vllm.ai/nightly
137
+ ```
138
+
139
+ Then you can inference MiniCPM4-0.5B with vLLM:
140
+ ```python
141
+ from transformers import AutoTokenizer
142
+ from vllm import LLM, SamplingParams
143
+
144
+ model_name = "openbmb/MiniCPM4-0.5B"
145
+ prompt = [{"role": "user", "content": "Please recommend 5 tourist attractions in Beijing. "}]
146
+
147
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
148
+ input_text = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
149
+
150
+ llm = LLM(
151
+ model=model_name,
152
+ trust_remote_code=True,
153
+ max_num_batched_tokens=32768,
154
+ dtype="bfloat16",
155
+ gpu_memory_utilization=0.8,
156
+ )
157
+ sampling_params = SamplingParams(top_p=0.7, temperature=0.7, max_tokens=1024, repetition_penalty=1.02)
158
+
159
+ outputs = llm.generate(prompts=input_text, sampling_params=sampling_params)
160
+
161
+ print(outputs[0].outputs[0].text)
162
+ ```
163
+
164
+ Also, you can start the inference server by running the following command:
165
+ > **Note**: In vLLM's chat API, `add_special_tokens` is `False` by default. This means important special tokens—such as the beginning-of-sequence (BOS) token—will not be added automatically. To ensure the input prompt is correctly formatted for the model, you should explicitly set `extra_body={"add_special_tokens": True}`.
166
+
167
+ ```bash
168
+ vllm serve openbmb/MiniCPM4-0.5B
169
+ ```
170
+
171
+ Then you can use the chat interface by running the following code:
172
+
173
+ ```python
174
+ import openai
175
+
176
+ client = openai.Client(base_url="http://localhost:8000/v1", api_key="EMPTY")
177
+
178
+ response = client.chat.completions.create(
179
+ model="openbmb/MiniCPM4-0.5B",
180
+ messages=[
181
+ {"role": "user", "content": "Write an article about Artificial Intelligence."},
182
+ ],
183
+ temperature=0.7,
184
+ max_tokens=1024,
185
+ extra_body=dict(add_special_tokens=True), # Ensures special tokens are added for chat template
186
+
187
+ )
188
+
189
+ print(response.choices[0].message.content)
190
+ ```
191
+
192
+
193
+ ## Evaluation Results
194
+ On two typical end-side chips, Jetson AGX Orin and RTX 4090, MiniCPM4 demonstrates significantly faster processing speed compared to similar-size models in long text processing tasks. As text length increases, MiniCPM4's efficiency advantage becomes more pronounced. On the Jetson AGX Orin platform, compared to Qwen3-8B, MiniCPM4 achieves approximately 7x decoding speed improvement.
195
+
196
+ ![benchmark](https://github.com/OpenBMB/MiniCPM/blob/main/assets/minicpm4/efficiency.png?raw=true)
197
+
198
+ #### Comprehensive Evaluation
199
+ MiniCPM4 launches end-side versions with 8B and 0.5B parameter scales, both achieving best-in-class performance in their respective categories.
200
+
201
+ ![benchmark](https://github.com/OpenBMB/MiniCPM/blob/main/assets/minicpm4/benchmark.png?raw=true)
202
+
203
+ #### Long Text Evaluation
204
+ MiniCPM4 is pre-trained on 32K long texts and achieves length extension through YaRN technology. In the 128K long text needle-in-a-haystack task, MiniCPM4 demonstrates outstanding performance.
205
+
206
+ ![long-niah](https://github.com/OpenBMB/MiniCPM/blob/main/assets/minicpm4/128k-niah.png?raw=true)
207
+
208
+ ## Statement
209
+ - As a language model, MiniCPM generates content by learning from a vast amount of text.
210
+ - However, it does not possess the ability to comprehend or express personal opinions or value judgments.
211
+ - Any content generated by MiniCPM does not represent the viewpoints or positions of the model developers.
212
+ - Therefore, when using content generated by MiniCPM, users should take full responsibility for evaluating and verifying it on their own.
213
+
214
+ ## LICENSE
215
+ - This repository and MiniCPM models are released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) License.
216
+
217
+ ## Citation
218
+ - Please cite our [paper](https://github.com/OpenBMB/MiniCPM/tree/main/report/MiniCPM_4_Technical_Report.pdf) if you find our work valuable.
219
+
220
+ ```bibtex
221
+ @article{minicpm4,
222
+ title={{MiniCPM4}: Ultra-Efficient LLMs on End Devices},
223
+ author={MiniCPM Team},
224
+ year={2025}
225
+ }
226
+ ```
added_tokens.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|execute_end|>": 73444,
3
+ "<|execute_start|>": 73443,
4
+ "<|fim_middle|>": 73446,
5
+ "<|fim_prefix|>": 73445,
6
+ "<|fim_suffix|>": 73447,
7
+ "<|im_end|>": 73440,
8
+ "<|im_start|>": 73441,
9
+ "<|tool_call|>": 73442
10
+ }
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openbmb/MiniCPM4-0.5B",
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, 73440],
15
+ "hidden_act": "silu",
16
+ "hidden_size": 1024,
17
+ "initializer_range": 0.1,
18
+ "intermediate_size": 4096,
19
+ "max_position_embeddings": 32768,
20
+ "num_attention_heads": 16,
21
+ "num_hidden_layers": 24,
22
+ "num_key_value_heads": 2,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": {
25
+ "rope_type": "longrope",
26
+ "long_factor": [1.0004360675811768, 1.0668443441390991, 1.1631425619125366, 1.3025742769241333, 1.5040205717086792, 1.7941505908966064, 2.2101221084594727, 2.802666664123535, 3.6389970779418945, 4.804192543029785, 6.39855432510376, 8.527148246765137, 11.277542114257812, 14.684998512268066, 18.69317054748535, 23.13019371032715, 27.72362518310547, 32.1606559753418, 36.168827056884766, 39.57627868652344, 42.32667541503906, 44.45526885986328, 46.04962921142578, 47.21482849121094, 48.05115509033203, 48.64370346069336, 49.05967712402344, 49.34980392456055, 49.551246643066406, 49.69068145751953, 49.78697967529297, 49.85338592529297],
27
+ "short_factor": [1.0004360675811768, 1.0668443441390991, 1.1631425619125366, 1.3025742769241333, 1.5040205717086792, 1.7941505908966064, 2.2101221084594727, 2.802666664123535, 3.6389970779418945, 4.804192543029785, 6.39855432510376, 8.527148246765137, 11.277542114257812, 14.684998512268066, 18.69317054748535, 23.13019371032715, 27.72362518310547, 32.1606559753418, 36.168827056884766, 39.57627868652344, 42.32667541503906, 44.45526885986328, 46.04962921142578, 47.21482849121094, 48.05115509033203, 48.64370346069336, 49.05967712402344, 49.34980392456055, 49.551246643066406, 49.69068145751953, 49.78697967529297, 49.85338592529297],
28
+ "original_max_position_embeddings": 32768
29
+ },
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.46.3",
32
+ "use_cache": true,
33
+ "vocab_size": 73448,
34
+ "scale_emb": 12,
35
+ "dim_model_base": 256,
36
+ "scale_depth": 1.4
37
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The OpenBMB Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ MiniCPM model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ MINICPM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
23
+
24
+
25
+ class MiniCPMConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`MiniCPMModel`]. It is used to instantiate an MiniCPM
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
29
+ defaults will yield a similar configuration to that of the MiniCPM-7B.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32000):
37
+ Vocabulary size of the MiniCPM model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`MiniCPMModel`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 11008):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer decoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer decoder.
47
+ num_key_value_heads (`int`, *optional*):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
54
+ `num_attention_heads`.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
58
+ The maximum sequence length that this model might ever be used with. MiniCPM 1 supports up to 2048 tokens,
59
+ MiniCPM 2 up to 4096, CodeMiniCPM up to 16384.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ pad_token_id (`int`, *optional*):
68
+ Padding token id.
69
+ bos_token_id (`int`, *optional*, defaults to 1):
70
+ Beginning of stream token id.
71
+ eos_token_id (`int`, *optional*, defaults to 2):
72
+ End of stream token id.
73
+ pretraining_tp (`int`, *optional*, defaults to 1):
74
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
75
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
76
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
77
+ issue](https://github.com/pytorch/pytorch/issues/76232).
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`Dict`, *optional*):
83
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
84
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
85
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
86
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
87
+ these scaling strategies behave:
88
+ https://www.reddit.com/r/LocalMiniCPM/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
89
+ experimental feature, subject to breaking API changes in future versions.
90
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
91
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
92
+ attention_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio for the attention probabilities.
94
+
95
+ ```python
96
+ >>> from transformers import MiniCPMModel, MiniCPMConfig
97
+
98
+ >>> # Initializing a MiniCPM minicpm-7b style configuration
99
+ >>> configuration = MiniCPMConfig()
100
+
101
+ >>> # Initializing a model from the minicpm-7b style configuration
102
+ >>> model = MiniCPMModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = 'minicpm'
109
+ keys_to_ignore_at_inference = ['past_key_values']
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=32000,
114
+ hidden_size=4096,
115
+ intermediate_size=11008,
116
+ num_hidden_layers=32,
117
+ num_attention_heads=32,
118
+ num_key_value_heads=None,
119
+ hidden_act='silu',
120
+ max_position_embeddings=2048,
121
+ initializer_range=0.02,
122
+ rms_norm_eps=1e-6,
123
+ use_cache=True,
124
+ pad_token_id=None,
125
+ bos_token_id=1,
126
+ eos_token_id=2,
127
+ pretraining_tp=1,
128
+ tie_word_embeddings=True,
129
+ rope_theta=10000.0,
130
+ rope_scaling=None,
131
+ attention_bias=False,
132
+ attention_dropout=0.0,
133
+ scale_emb=1,
134
+ dim_model_base=1,
135
+ scale_depth=1,
136
+ mup_denominator=None,
137
+ sparse_config=None,
138
+ **kwargs):
139
+
140
+ self.vocab_size = vocab_size
141
+ self.max_position_embeddings = max_position_embeddings
142
+ self.hidden_size = hidden_size
143
+ self.intermediate_size = intermediate_size
144
+ self.num_hidden_layers = num_hidden_layers
145
+ self.num_attention_heads = num_attention_heads
146
+
147
+ # for backward compatibility
148
+ if num_key_value_heads is None:
149
+ num_key_value_heads = num_attention_heads
150
+
151
+ self.num_key_value_heads = num_key_value_heads
152
+ self.hidden_act = hidden_act
153
+ self.initializer_range = initializer_range
154
+ self.rms_norm_eps = rms_norm_eps
155
+ self.pretraining_tp = pretraining_tp
156
+ self.use_cache = use_cache
157
+ self.rope_theta = rope_theta
158
+ self.rope_scaling = rope_scaling
159
+ # self._rope_scaling_validation()
160
+ self.attention_bias = attention_bias
161
+ self.attention_dropout = attention_dropout
162
+ self.scale_emb = scale_emb
163
+ self.dim_model_base = dim_model_base
164
+ self.scale_depth = scale_depth
165
+ # only used for Eagle Head
166
+ self.mup_denominator = mup_denominator
167
+
168
+ # sparse config
169
+ self.sparse_config = sparse_config
170
+
171
+ super().__init__(
172
+ pad_token_id=pad_token_id,
173
+ bos_token_id=bos_token_id,
174
+ eos_token_id=eos_token_id,
175
+ tie_word_embeddings=tie_word_embeddings,
176
+ **kwargs,
177
+ )
178
+ try:
179
+ import flash_attn
180
+ self._attn_implementation = 'flash_attention_2'
181
+ except:
182
+ pass
183
+
184
+ def _rope_scaling_validation(self):
185
+ """
186
+ Validate the `rope_scaling` configuration.
187
+ """
188
+ if self.rope_scaling is None:
189
+ return
190
+
191
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
192
+ raise ValueError(
193
+ '`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
194
+ f'got {self.rope_scaling}'
195
+ )
196
+ rope_scaling_type = self.rope_scaling.get('type', None)
197
+ rope_scaling_factor = self.rope_scaling.get('factor', None)
198
+ if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
199
+ raise ValueError(
200
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
201
+ )
202
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
203
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 2,
6
+ 73440
7
+ ],
8
+ "pad_token_id": 2,
9
+ "temperature": 0.8,
10
+ "top_p": 0.8,
11
+ "transformers_version": "4.46.1"
12
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef74f4de1d1c580dd64e425d11f29881b9fd39f9be16a485150f727d4583181c
3
+ size 867772648
modeling_minicpm.py ADDED
@@ -0,0 +1,1514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The OpenBMB Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch MiniCPM model."""
16
+ import math
17
+ import re
18
+ import warnings
19
+ from typing import Any, Dict, List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+ from transformers.activations import ACT2FN
27
+ from transformers.cache_utils import Cache, DynamicCache, CacheLayerMixin, DynamicLayer
28
+ from transformers.modeling_attn_mask_utils import (
29
+ AttentionMaskConverter,
30
+ _prepare_4d_attention_mask,
31
+ _prepare_4d_causal_attention_mask,
32
+ _prepare_4d_causal_attention_mask_for_sdpa,
33
+ )
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
41
+ from transformers.utils import (
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from transformers.utils.import_utils import is_torch_fx_available
49
+
50
+ from .configuration_minicpm import MiniCPMConfig
51
+
52
+ try:
53
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+ except:
56
+ pass
57
+
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
+
87
+
88
+ # @torch.jit.script # type: ignore
89
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
90
+ old_dtype = hidden.dtype
91
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
92
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
93
+ return hidden * weight
94
+
95
+
96
+ class MiniCPMRMSNorm(nn.Module):
97
+ def __init__(self, hidden_size, eps=1e-6):
98
+ """
99
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
100
+ """
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
107
+
108
+
109
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
110
+
111
+
112
+ class MiniCPMRotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
120
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
121
+
122
+ # Build here to make `torch.jit.trace` work.
123
+ self._set_cos_sin_cache(
124
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
131
+ freqs = torch.outer(t, self.inv_freq)
132
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+
135
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ class MiniCPMLongRoPE(MiniCPMRotaryEmbedding):
150
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
151
+
152
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, short_factor=None, long_factor=None, original_max_position_embeddings=None):
153
+ self.short_factor = short_factor
154
+ self.long_factor = long_factor
155
+ self.original_max_position_embeddings = original_max_position_embeddings
156
+ scale = (max_position_embeddings / self.original_max_position_embeddings)
157
+ self.scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
158
+ super().__init__(dim, max_position_embeddings, base, device)
159
+
160
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
161
+ self.max_seq_len_cached = seq_len
162
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
163
+ if seq_len > self.original_max_position_embeddings:
164
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=device)
165
+ else:
166
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=device)
167
+
168
+ freqs = torch.mul(
169
+ torch.outer(t, 1.0 / ext_factors).to(device=device),
170
+ self.inv_freq.to(device=device).to(dtype)
171
+ )
172
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
173
+ emb = torch.cat((freqs, freqs), dim=-1)
174
+ self.register_buffer('cos_cached', emb.cos().to(dtype) * self.scaling_factor, persistent=False)
175
+ self.register_buffer('sin_cached', emb.sin().to(dtype) * self.scaling_factor, persistent=False)
176
+
177
+
178
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
179
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
188
+ t = t / self.scaling_factor
189
+
190
+ freqs = torch.outer(t, self.inv_freq)
191
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
192
+ emb = torch.cat((freqs, freqs), dim=-1)
193
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
194
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
195
+
196
+
197
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
198
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
199
+
200
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
201
+ self.scaling_factor = scaling_factor
202
+ super().__init__(dim, max_position_embeddings, base, device)
203
+
204
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
205
+ self.max_seq_len_cached = seq_len
206
+
207
+ if seq_len > self.max_position_embeddings:
208
+ base = self.base * (
209
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
210
+ ) ** (self.dim / (self.dim - 2))
211
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
212
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
213
+
214
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
215
+
216
+ freqs = torch.outer(t, self.inv_freq)
217
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
218
+ emb = torch.cat((freqs, freqs), dim=-1)
219
+
220
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
221
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
222
+
223
+
224
+ def rotate_half(x):
225
+ """Rotates half the hidden dims of the input."""
226
+ x1 = x[..., : x.shape[-1] // 2]
227
+ x2 = x[..., x.shape[-1] // 2:]
228
+ return torch.cat((-x2, x1), dim=-1)
229
+
230
+
231
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
232
+ """Applies Rotary Position Embedding to the query and key tensors.
233
+
234
+ Args:
235
+ q (`torch.Tensor`): The query tensor.
236
+ k (`torch.Tensor`): The key tensor.
237
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
238
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
239
+ position_ids (`torch.Tensor`):
240
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
241
+ used to pass offsetted position ids when working with a KV-cache.
242
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
243
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
244
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
245
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
246
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
247
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
248
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
249
+ Returns:
250
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
251
+ """
252
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
253
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
254
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
255
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
256
+ orig_dtype = k.dtype
257
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
258
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
259
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
260
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
261
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
262
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
263
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
264
+
265
+
266
+ class MiniCPMMLP(nn.Module):
267
+ def __init__(self, config):
268
+ super().__init__()
269
+ self.config = config
270
+ self.hidden_size = config.hidden_size
271
+ self.intermediate_size = config.intermediate_size
272
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
273
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
274
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
275
+ self.act_fn = ACT2FN[config.hidden_act]
276
+
277
+ def forward(self, x):
278
+ if self.config.pretraining_tp > 1:
279
+ slice = self.intermediate_size // self.config.pretraining_tp
280
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
281
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
282
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
283
+
284
+ gate_proj = torch.cat(
285
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
286
+ )
287
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
288
+
289
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
290
+ down_proj = [
291
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
292
+ ]
293
+ down_proj = sum(down_proj)
294
+ else:
295
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
296
+
297
+ return down_proj
298
+
299
+ def _unpad_one_tensor(hidden_states, attention_mask):
300
+ # Unpad the hidden states using the indices
301
+ indices, cu_seqlens, max_seqlen_in_batch = _get_unpad_data(attention_mask)
302
+ batch_size, seq_len = hidden_states.shape[:2]
303
+
304
+ # Get the remaining dimensions
305
+ remaining_dims = hidden_states.shape[2:]
306
+
307
+ # Reshape to (batch_size * seq_len, *remaining_dims)
308
+ reshaped_states = hidden_states.reshape(batch_size * seq_len, *remaining_dims)
309
+
310
+ # Apply unpadding using indices
311
+ unpadded_states = index_first_axis(reshaped_states, indices)
312
+
313
+ return unpadded_states, indices, cu_seqlens, max_seqlen_in_batch
314
+
315
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
316
+ """
317
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
318
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
319
+ """
320
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
321
+ if n_rep == 1:
322
+ return hidden_states
323
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
324
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
325
+
326
+
327
+ class MiniCPMAttention(nn.Module):
328
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
329
+
330
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
331
+ super().__init__()
332
+ self.config = config
333
+ self.layer_idx = layer_idx
334
+ if layer_idx is None:
335
+ logger.warning_once(
336
+ f'Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will '
337
+ 'to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` '
338
+ 'when creating this class.'
339
+ )
340
+
341
+ self.attention_dropout = config.attention_dropout
342
+ self.hidden_size = config.hidden_size
343
+ self.num_heads = config.num_attention_heads
344
+ self.head_dim = self.hidden_size // self.num_heads
345
+ self.num_key_value_heads = config.num_key_value_heads
346
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
347
+ self.max_position_embeddings = config.max_position_embeddings
348
+ self.rope_theta = config.rope_theta
349
+ self.is_causal = True
350
+
351
+ if (self.head_dim * self.num_heads) != self.hidden_size:
352
+ raise ValueError(
353
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
354
+ f' and `num_heads`: {self.num_heads}).'
355
+ )
356
+
357
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
358
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
359
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
360
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
361
+ self._init_rope()
362
+
363
+ def _init_rope(self):
364
+ if self.config.rope_scaling is None:
365
+ self.rotary_emb = MiniCPMRotaryEmbedding(
366
+ self.head_dim,
367
+ max_position_embeddings=self.max_position_embeddings,
368
+ base=self.rope_theta,
369
+ )
370
+ else:
371
+ scaling_type = self.config.rope_scaling['rope_type']
372
+ scaling_factor = self.config.rope_scaling.get('factor', None)
373
+ if scaling_type == 'linear':
374
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
375
+ self.head_dim,
376
+ max_position_embeddings=self.max_position_embeddings,
377
+ scaling_factor=scaling_factor,
378
+ base=self.rope_theta,
379
+ )
380
+ elif scaling_type == 'dynamic':
381
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
382
+ self.head_dim,
383
+ max_position_embeddings=self.max_position_embeddings,
384
+ scaling_factor=scaling_factor,
385
+ base=self.rope_theta,
386
+ )
387
+ elif scaling_type == 'longrope':
388
+ self.rotary_emb = MiniCPMLongRoPE(
389
+ self.head_dim,
390
+ max_position_embeddings=self.max_position_embeddings,
391
+ short_factor=self.config.rope_scaling['short_factor'],
392
+ long_factor=self.config.rope_scaling['long_factor'],
393
+ base=self.rope_theta,
394
+ original_max_position_embeddings=self.config.rope_scaling['original_max_position_embeddings']
395
+ )
396
+ else:
397
+ raise ValueError(f'Unknown RoPE scaling type {scaling_type}')
398
+
399
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
400
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
401
+
402
+ def forward(
403
+ self,
404
+ hidden_states: torch.Tensor,
405
+ attention_mask: Optional[torch.Tensor] = None,
406
+ position_ids: Optional[torch.LongTensor] = None,
407
+ past_key_value: Optional[Cache] = None,
408
+ output_attentions: bool = False,
409
+ use_cache: bool = False,
410
+ **kwargs,
411
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
412
+ if 'padding_mask' in kwargs:
413
+ warnings.warn(
414
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
415
+ )
416
+
417
+ bsz, q_len, _ = hidden_states.size()
418
+
419
+ if self.config.pretraining_tp > 1:
420
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
421
+ query_slices = self.q_proj.weight.split(
422
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
423
+ )
424
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
425
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
426
+
427
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
428
+ query_states = torch.cat(query_states, dim=-1)
429
+
430
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
431
+ key_states = torch.cat(key_states, dim=-1)
432
+
433
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
434
+ value_states = torch.cat(value_states, dim=-1)
435
+
436
+ else:
437
+ query_states = self.q_proj(hidden_states)
438
+ key_states = self.k_proj(hidden_states)
439
+ value_states = self.v_proj(hidden_states)
440
+
441
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
442
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
443
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
444
+
445
+ kv_seq_len = position_ids.max().item() + 1
446
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
447
+
448
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
449
+
450
+ if past_key_value is not None:
451
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
452
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
453
+
454
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
455
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
456
+
457
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
458
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
459
+ raise ValueError(
460
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
461
+ f' {attn_weights.size()}'
462
+ )
463
+
464
+ if attention_mask is not None:
465
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
466
+ raise ValueError(
467
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
468
+ )
469
+ attn_weights = attn_weights + attention_mask
470
+
471
+ # upcast attention to fp32
472
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
473
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
474
+ attn_output = torch.matmul(attn_weights, value_states)
475
+
476
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
477
+ raise ValueError(
478
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
479
+ f' {attn_output.size()}'
480
+ )
481
+
482
+ attn_output = attn_output.transpose(1, 2).contiguous()
483
+
484
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
485
+
486
+ if self.config.pretraining_tp > 1:
487
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
488
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
489
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
490
+ else:
491
+ attn_output = self.o_proj(attn_output)
492
+
493
+ if not output_attentions:
494
+ attn_weights = None
495
+
496
+ return attn_output, attn_weights, past_key_value
497
+
498
+
499
+ class MiniCPMFlashAttention2(MiniCPMAttention):
500
+ """
501
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
502
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
503
+ flash attention and deal with padding tokens in case the input contains any of them.
504
+ """
505
+
506
+ def __init__(self, *args, **kwargs):
507
+ super().__init__(*args, **kwargs)
508
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
509
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, 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.
510
+ # 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).
511
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ attention_mask: Optional[torch.LongTensor] = None,
517
+ position_ids: Optional[torch.LongTensor] = None,
518
+ past_key_value: Optional[Cache] = None,
519
+ output_attentions: bool = False,
520
+ use_cache: bool = False,
521
+ **kwargs,
522
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
523
+ # MiniCPMFlashAttention2 attention does not support output_attentions
524
+ if 'padding_mask' in kwargs:
525
+ warnings.warn(
526
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
527
+ )
528
+
529
+ # overwrite attention_mask with padding_mask
530
+ attention_mask = kwargs.pop('padding_mask')
531
+
532
+ output_attentions = False
533
+
534
+ bsz, q_len, _ = hidden_states.size()
535
+
536
+ query_states = self.q_proj(hidden_states)
537
+ key_states = self.k_proj(hidden_states)
538
+ value_states = self.v_proj(hidden_states)
539
+
540
+ # Flash attention requires the input to have the shape
541
+ # batch_size x seq_length x head_dim x hidden_dim
542
+ # therefore we just need to keep the original shape
543
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
544
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
545
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
546
+
547
+ kv_seq_len = position_ids.max().item() + 1
548
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
549
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
550
+
551
+ if past_key_value is not None:
552
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
553
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
554
+
555
+ # 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
556
+ # to be able to avoid many of these transpose/reshape/view.
557
+ query_states = query_states.transpose(1, 2)
558
+ key_states = key_states.transpose(1, 2)
559
+ value_states = value_states.transpose(1, 2)
560
+
561
+ dropout_rate = self.attention_dropout if self.training else 0.0
562
+
563
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
564
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
565
+ # cast them back in the correct dtype just to be sure everything works as expected.
566
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
567
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
568
+
569
+ input_dtype = query_states.dtype
570
+ if input_dtype == torch.float32:
571
+ # Handle the case where the model is quantized
572
+ if hasattr(self.config, '_pre_quantization_dtype'):
573
+ target_dtype = self.config._pre_quantization_dtype
574
+ else:
575
+ target_dtype = self.q_proj.weight.dtype
576
+
577
+ logger.warning_once(
578
+ f'The input hidden states seems to be silently casted in float32, this might be related to'
579
+ f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in'
580
+ f' {target_dtype}.'
581
+ )
582
+
583
+ query_states = query_states.to(target_dtype)
584
+ key_states = key_states.to(target_dtype)
585
+ value_states = value_states.to(target_dtype)
586
+
587
+ attn_output = self._flash_attention_forward(
588
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
589
+ )
590
+
591
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
592
+ attn_output = self.o_proj(attn_output)
593
+
594
+ if not output_attentions:
595
+ attn_weights = None
596
+
597
+ return attn_output, attn_weights, past_key_value
598
+
599
+ def _flash_attention_forward(
600
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
601
+ ):
602
+ """
603
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
604
+ first unpad the input, then computes the attention scores and pad the final attention scores.
605
+
606
+ Args:
607
+ query_states (`torch.Tensor`):
608
+ Input query states to be passed to Flash Attention API
609
+ key_states (`torch.Tensor`):
610
+ Input key states to be passed to Flash Attention API
611
+ value_states (`torch.Tensor`):
612
+ Input value states to be passed to Flash Attention API
613
+ attention_mask (`torch.Tensor`):
614
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
615
+ position of padding tokens and 1 for the position of non-padding tokens.
616
+ dropout (`int`, *optional*):
617
+ Attention dropout
618
+ softmax_scale (`float`, *optional*):
619
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
620
+ """
621
+ if not self._flash_attn_uses_top_left_mask:
622
+ causal = self.is_causal
623
+ else:
624
+ # 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__.
625
+ causal = self.is_causal and query_length != 1
626
+ # Contains at least one padding token in the sequence
627
+ if attention_mask is not None:
628
+ batch_size = query_states.shape[0]
629
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
630
+ query_states, key_states, value_states, attention_mask, query_length
631
+ )
632
+
633
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
634
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
635
+ attn_output_unpad = flash_attn_varlen_func(
636
+ query_states,
637
+ key_states,
638
+ value_states,
639
+ cu_seqlens_q=cu_seqlens_q,
640
+ cu_seqlens_k=cu_seqlens_k,
641
+ max_seqlen_q=max_seqlen_in_batch_q,
642
+ max_seqlen_k=max_seqlen_in_batch_k,
643
+ dropout_p=dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ )
647
+
648
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
649
+ else:
650
+ attn_output = flash_attn_func(
651
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
652
+ )
653
+
654
+ return attn_output
655
+
656
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
657
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
658
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
659
+
660
+ key_layer = index_first_axis(
661
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
662
+ )
663
+ value_layer = index_first_axis(
664
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
665
+ )
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ class MiniCPMSdpaAttention(MiniCPMAttention):
696
+ """
697
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
698
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
699
+ SDPA API.
700
+ """
701
+
702
+ # Adapted from MiniCPMAttention.forward
703
+ def forward(
704
+ self,
705
+ hidden_states: torch.Tensor,
706
+ attention_mask: Optional[torch.Tensor] = None,
707
+ position_ids: Optional[torch.LongTensor] = None,
708
+ past_key_value: Optional[Cache] = None,
709
+ output_attentions: bool = False,
710
+ use_cache: bool = False,
711
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
712
+ if output_attentions:
713
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
714
+ logger.warning_once(
715
+ '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, '
716
+ '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.'
717
+ )
718
+ return super().forward(
719
+ hidden_states=hidden_states,
720
+ attention_mask=attention_mask,
721
+ position_ids=position_ids,
722
+ past_key_value=past_key_value,
723
+ output_attentions=output_attentions,
724
+ use_cache=use_cache,
725
+ )
726
+
727
+ bsz, q_len, _ = hidden_states.size()
728
+
729
+ query_states = self.q_proj(hidden_states)
730
+ key_states = self.k_proj(hidden_states)
731
+ value_states = self.v_proj(hidden_states)
732
+
733
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
734
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
735
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+
737
+ kv_seq_len = position_ids.max().item() + 1
738
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
739
+
740
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
741
+
742
+ if past_key_value is not None:
743
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
744
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
745
+
746
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
747
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
748
+
749
+ if attention_mask is not None:
750
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
751
+ raise ValueError(
752
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
753
+ )
754
+
755
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
756
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
757
+ if query_states.device.type == 'cuda' and attention_mask is not None:
758
+ query_states = query_states.contiguous()
759
+ key_states = key_states.contiguous()
760
+ value_states = value_states.contiguous()
761
+
762
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
763
+ query_states,
764
+ key_states,
765
+ value_states,
766
+ attn_mask=attention_mask,
767
+ dropout_p=self.attention_dropout if self.training else 0.0,
768
+ # 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.
769
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
770
+ )
771
+
772
+ attn_output = attn_output.transpose(1, 2).contiguous()
773
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
774
+
775
+ attn_output = self.o_proj(attn_output)
776
+
777
+ return attn_output, None, past_key_value
778
+
779
+
780
+ MINICPM_ATTENTION_CLASSES = {
781
+ 'eager': MiniCPMAttention,
782
+ 'flash_attention_2': MiniCPMFlashAttention2,
783
+ 'sdpa': MiniCPMSdpaAttention,
784
+ }
785
+
786
+
787
+ class MiniCPMDecoderLayer(nn.Module):
788
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
789
+ super().__init__()
790
+ self.hidden_size = config.hidden_size
791
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
792
+
793
+ self.mlp = MiniCPMMLP(config)
794
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
795
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
796
+
797
+ self.scale_depth = config.scale_depth
798
+ self.num_hidden_layers = config.num_hidden_layers
799
+
800
+ def forward(
801
+ self,
802
+ hidden_states: torch.Tensor,
803
+ attention_mask: Optional[torch.Tensor] = None,
804
+ position_ids: Optional[torch.LongTensor] = None,
805
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
806
+ output_attentions: Optional[bool] = False,
807
+ use_cache: Optional[bool] = False,
808
+ **kwargs,
809
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
810
+ """
811
+ Args:
812
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
813
+ attention_mask (`torch.FloatTensor`, *optional*):
814
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
815
+ query_sequence_length, key_sequence_length)` if default attention is used.
816
+ output_attentions (`bool`, *optional*):
817
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
818
+ returned tensors for more detail.
819
+ use_cache (`bool`, *optional*):
820
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
821
+ (see `past_key_values`).
822
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
823
+ """
824
+ if 'padding_mask' in kwargs:
825
+ warnings.warn(
826
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
827
+ )
828
+
829
+ residual = hidden_states
830
+ hidden_states = self.input_layernorm(hidden_states)
831
+ # Self Attention
832
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
833
+ hidden_states=hidden_states,
834
+ attention_mask=attention_mask,
835
+ position_ids=position_ids,
836
+ past_key_value=past_key_value,
837
+ output_attentions=output_attentions,
838
+ use_cache=use_cache,
839
+ **kwargs,
840
+ )
841
+
842
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
843
+
844
+ # Fully Connected
845
+ residual = hidden_states
846
+ hidden_states = self.post_attention_layernorm(hidden_states)
847
+
848
+ hidden_states = self.mlp(hidden_states)
849
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
850
+
851
+ outputs = (hidden_states,)
852
+
853
+ if output_attentions:
854
+ outputs += (self_attn_weights,)
855
+
856
+ if use_cache:
857
+ outputs += (present_key_value,)
858
+
859
+ return outputs
860
+
861
+
862
+ MINICPM_START_DOCSTRING = r"""
863
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
864
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
865
+ etc.)
866
+
867
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
868
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
869
+ and behavior.
870
+
871
+ Parameters:
872
+ config ([`MiniCPMConfig`]):
873
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
874
+ load the weights associated with the model, only the configuration. Check out the
875
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
876
+ """
877
+
878
+
879
+ @add_start_docstrings(
880
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
881
+ MINICPM_START_DOCSTRING,
882
+ )
883
+ class MiniCPMPreTrainedModel(PreTrainedModel):
884
+ config_class = MiniCPMConfig
885
+ base_model_prefix = 'model'
886
+ supports_gradient_checkpointing = True
887
+ _no_split_modules = ['MiniCPMDecoderLayer']
888
+ _skip_keys_device_placement = 'past_key_values'
889
+ _supports_flash_attn_2 = True
890
+ _supports_sdpa = True
891
+ _supports_cache_class = True
892
+
893
+ def _init_weights(self, module):
894
+ std = self.config.initializer_range
895
+ if isinstance(module, nn.Linear):
896
+ module.weight.data.normal_(mean=0.0, std=std)
897
+ if module.bias is not None:
898
+ module.bias.data.zero_()
899
+ elif isinstance(module, nn.Embedding):
900
+ module.weight.data.normal_(mean=0.0, std=std)
901
+ if module.padding_idx is not None:
902
+ module.weight.data[module.padding_idx].zero_()
903
+
904
+
905
+ MINICPM_INPUTS_DOCSTRING = r"""
906
+ Args:
907
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
908
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
909
+ it.
910
+
911
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
912
+ [`PreTrainedTokenizer.__call__`] for details.
913
+
914
+ [What are input IDs?](../glossary#input-ids)
915
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
916
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
917
+
918
+ - 1 for tokens that are **not masked**,
919
+ - 0 for tokens that are **masked**.
920
+
921
+ [What are attention masks?](../glossary#attention-mask)
922
+
923
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
924
+ [`PreTrainedTokenizer.__call__`] for details.
925
+
926
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
927
+ `past_key_values`).
928
+
929
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
930
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
931
+ information on the default strategy.
932
+
933
+ - 1 indicates the head is **not masked**,
934
+ - 0 indicates the head is **masked**.
935
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
936
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
937
+ config.n_positions - 1]`.
938
+
939
+ [What are position IDs?](../glossary#position-ids)
940
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
941
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
942
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
943
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
944
+
945
+ Two formats are allowed:
946
+ - a [`~cache_utils.Cache`] instance;
947
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
948
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
949
+ cache format.
950
+
951
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
952
+ legacy cache format will be returned.
953
+
954
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
955
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
956
+ of shape `(batch_size, sequence_length)`.
957
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
958
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
959
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
960
+ model's internal embedding lookup matrix.
961
+ use_cache (`bool`, *optional*):
962
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
963
+ `past_key_values`).
964
+ output_attentions (`bool`, *optional*):
965
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
966
+ tensors for more detail.
967
+ output_hidden_states (`bool`, *optional*):
968
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
969
+ more detail.
970
+ return_dict (`bool`, *optional*):
971
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
972
+ """
973
+
974
+
975
+ @add_start_docstrings(
976
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
977
+ MINICPM_START_DOCSTRING,
978
+ )
979
+ class MiniCPMModel(MiniCPMPreTrainedModel):
980
+ """
981
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
982
+
983
+ Args:
984
+ config: MiniCPMConfig
985
+ """
986
+
987
+ def __init__(self, config: MiniCPMConfig):
988
+ super().__init__(config)
989
+ self.padding_idx = config.pad_token_id
990
+ self.vocab_size = config.vocab_size
991
+
992
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
993
+ self.layers = nn.ModuleList(
994
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
995
+ )
996
+ self._use_sdpa = config._attn_implementation == 'sdpa'
997
+ self._use_flash_attention_2 = config._attn_implementation == 'flash_attention_2'
998
+
999
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1000
+
1001
+ self.gradient_checkpointing = False
1002
+ # Initialize weights and apply final processing
1003
+ self.post_init()
1004
+
1005
+ def get_input_embeddings(self):
1006
+ return self.embed_tokens
1007
+
1008
+ def set_input_embeddings(self, value):
1009
+ self.embed_tokens = value
1010
+
1011
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1012
+ def forward(
1013
+ self,
1014
+ input_ids: torch.LongTensor = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ use_cache: Optional[bool] = None,
1020
+ output_attentions: Optional[bool] = None,
1021
+ output_hidden_states: Optional[bool] = None,
1022
+ return_dict: Optional[bool] = None,
1023
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1024
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1025
+ output_hidden_states = (
1026
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1027
+ )
1028
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1029
+
1030
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1031
+
1032
+ # retrieve input_ids and inputs_embeds
1033
+ if input_ids is not None and inputs_embeds is not None:
1034
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
1035
+ elif input_ids is not None:
1036
+ batch_size, seq_length = input_ids.shape[:2]
1037
+ elif inputs_embeds is not None:
1038
+ batch_size, seq_length = inputs_embeds.shape[:2]
1039
+ else:
1040
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
1041
+
1042
+ if self.gradient_checkpointing and self.training:
1043
+ if use_cache:
1044
+ logger.warning_once(
1045
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
1046
+ )
1047
+ use_cache = False
1048
+
1049
+ past_key_values_length = 0
1050
+
1051
+ if use_cache:
1052
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1053
+ if use_legacy_cache:
1054
+ raise ValueError(
1055
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1056
+ )
1057
+
1058
+ # Calculate the usable length of past key values
1059
+ past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, Cache) else 0
1060
+
1061
+
1062
+ if position_ids is None:
1063
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1064
+ position_ids = torch.arange(
1065
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1066
+ )
1067
+ position_ids = position_ids.unsqueeze(0)
1068
+
1069
+ if inputs_embeds is None:
1070
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1071
+
1072
+ if self._use_flash_attention_2:
1073
+ # 2d mask is passed through the layers
1074
+ # attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1075
+ if attention_mask is None:
1076
+ raise ValueError(
1077
+ f'need attention_mask for flash attention, but got {attention_mask}.'
1078
+ )
1079
+ elif self._use_sdpa and not output_attentions:
1080
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1081
+ # the manual implementation that requires a 4D causal mask in all cases.
1082
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1083
+ attention_mask,
1084
+ (batch_size, seq_length),
1085
+ inputs_embeds,
1086
+ past_key_values_length,
1087
+ )
1088
+ else:
1089
+ # 4d mask is passed through the layers
1090
+ attention_mask = _prepare_4d_causal_attention_mask(
1091
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1092
+ )
1093
+
1094
+ # embed positions
1095
+ hidden_states = inputs_embeds
1096
+
1097
+ # decoder layers
1098
+ all_hidden_states = () if output_hidden_states else None
1099
+ all_self_attns = () if output_attentions else None
1100
+ next_decoder_cache = None
1101
+
1102
+ for decoder_layer in self.layers:
1103
+ if output_hidden_states:
1104
+ all_hidden_states += (hidden_states,)
1105
+
1106
+ if self.gradient_checkpointing and self.training:
1107
+ layer_outputs = self._gradient_checkpointing_func(
1108
+ decoder_layer.__call__,
1109
+ hidden_states,
1110
+ attention_mask,
1111
+ position_ids,
1112
+ past_key_values,
1113
+ output_attentions,
1114
+ use_cache,
1115
+ )
1116
+ else:
1117
+ layer_outputs = decoder_layer(
1118
+ hidden_states,
1119
+ attention_mask=attention_mask,
1120
+ position_ids=position_ids,
1121
+ past_key_value=past_key_values,
1122
+ output_attentions=output_attentions,
1123
+ use_cache=use_cache,
1124
+ )
1125
+
1126
+ hidden_states = layer_outputs[0]
1127
+
1128
+ if use_cache:
1129
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1130
+
1131
+ if output_attentions:
1132
+ all_self_attns += (layer_outputs[1],)
1133
+
1134
+ hidden_states = self.norm(hidden_states)
1135
+
1136
+ # add hidden states from the last decoder layer
1137
+ if output_hidden_states:
1138
+ all_hidden_states += (hidden_states,)
1139
+
1140
+ next_cache = None
1141
+ if use_cache:
1142
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1143
+ if not return_dict:
1144
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1145
+ return BaseModelOutputWithPast(
1146
+ last_hidden_state=hidden_states,
1147
+ past_key_values=next_cache,
1148
+ hidden_states=all_hidden_states,
1149
+ attentions=all_self_attns,
1150
+ )
1151
+
1152
+
1153
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1154
+ _tied_weights_keys = ['lm_head.weight']
1155
+
1156
+ def __init__(self, config):
1157
+ super().__init__(config)
1158
+ self.model = MiniCPMModel(config)
1159
+ self.vocab_size = config.vocab_size
1160
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1161
+
1162
+ # Initialize weights and apply final processing
1163
+ self.post_init()
1164
+
1165
+ def get_input_embeddings(self):
1166
+ return self.model.embed_tokens
1167
+
1168
+ def set_input_embeddings(self, value):
1169
+ self.model.embed_tokens = value
1170
+
1171
+ def get_output_embeddings(self):
1172
+ return self.lm_head
1173
+
1174
+ def set_output_embeddings(self, new_embeddings):
1175
+ self.lm_head = new_embeddings
1176
+
1177
+ def set_decoder(self, decoder):
1178
+ self.model = decoder
1179
+
1180
+ def get_decoder(self):
1181
+ return self.model
1182
+
1183
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1184
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1185
+ def forward(
1186
+ self,
1187
+ input_ids: torch.LongTensor = None,
1188
+ attention_mask: Optional[torch.Tensor] = None,
1189
+ position_ids: Optional[torch.LongTensor] = None,
1190
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1191
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1192
+ labels: Optional[torch.LongTensor] = None,
1193
+ use_cache: Optional[bool] = None,
1194
+ output_attentions: Optional[bool] = None,
1195
+ output_hidden_states: Optional[bool] = None,
1196
+ return_dict: Optional[bool] = None,
1197
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1198
+ **kwargs,
1199
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1200
+ r"""
1201
+ Args:
1202
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1203
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1204
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1205
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1206
+
1207
+ Returns:
1208
+
1209
+ Example:
1210
+
1211
+ ```python
1212
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1213
+
1214
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1215
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1216
+
1217
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1218
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1219
+
1220
+ >>> # Generate
1221
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1222
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1223
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1224
+ ```"""
1225
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1226
+ output_hidden_states = (
1227
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1228
+ )
1229
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1230
+
1231
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1232
+ outputs = self.model(
1233
+ input_ids=input_ids,
1234
+ attention_mask=attention_mask,
1235
+ position_ids=position_ids,
1236
+ past_key_values=past_key_values,
1237
+ inputs_embeds=inputs_embeds,
1238
+ use_cache=use_cache,
1239
+ output_attentions=output_attentions,
1240
+ output_hidden_states=output_hidden_states,
1241
+ return_dict=return_dict,
1242
+ )
1243
+
1244
+ hidden_states = outputs[0]
1245
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1246
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1247
+ hidden_states = hidden_states[:, slice_indices, :].contiguous()
1248
+ if self.config.pretraining_tp > 1:
1249
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1250
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1251
+ logits = torch.cat(logits, dim=-1)
1252
+ else:
1253
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1254
+ logits = logits.float()
1255
+
1256
+ loss = None
1257
+ if labels is not None:
1258
+ # Shift so that tokens < n predict n
1259
+ shift_logits = logits[..., :-1, :].contiguous()
1260
+ shift_labels = labels[..., 1:].contiguous()
1261
+ # Flatten the tokens
1262
+ loss_fct = CrossEntropyLoss()
1263
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1264
+ shift_labels = shift_labels.view(-1)
1265
+ # Enable model parallelism
1266
+ shift_labels = shift_labels.to(shift_logits.device)
1267
+ loss = loss_fct(shift_logits, shift_labels)
1268
+
1269
+ if not return_dict:
1270
+ output = (logits,) + outputs[1:]
1271
+ return (loss,) + output if loss is not None else output
1272
+
1273
+ return CausalLMOutputWithPast(
1274
+ loss=loss,
1275
+ logits=logits,
1276
+ past_key_values=outputs.past_key_values,
1277
+ hidden_states=outputs.hidden_states,
1278
+ attentions=outputs.attentions,
1279
+ )
1280
+
1281
+ def prepare_inputs_for_generation(
1282
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1283
+ ):
1284
+ if past_key_values is not None:
1285
+ if isinstance(past_key_values, Cache):
1286
+ # Use the new Cache class methods
1287
+ cache_length = past_key_values.get_seq_length()
1288
+
1289
+
1290
+ past_length = cache_length
1291
+ max_cache_length = None
1292
+ else:
1293
+ raise ValueError(
1294
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1295
+ )
1296
+
1297
+ # Keep only the unprocessed tokens:
1298
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1299
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1300
+ # input)
1301
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1302
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1303
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1304
+ # input_ids based on the past_length.
1305
+ elif past_length < input_ids.shape[1]:
1306
+ input_ids = input_ids[:, past_length:]
1307
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1308
+
1309
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1310
+ if (
1311
+ max_cache_length is not None
1312
+ and attention_mask is not None
1313
+ and cache_length + input_ids.shape[1] > max_cache_length
1314
+ ):
1315
+ attention_mask = attention_mask[:, -max_cache_length:]
1316
+
1317
+ position_ids = kwargs.get('position_ids', None)
1318
+ if attention_mask is not None and position_ids is None:
1319
+ # create position_ids on the fly for batch generation
1320
+ position_ids = attention_mask.long().cumsum(-1) - 1
1321
+ position_ids.masked_fill_(attention_mask == 0, 1)
1322
+ if past_key_values:
1323
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1324
+
1325
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1326
+ if inputs_embeds is not None and past_key_values is None:
1327
+ model_inputs = {'inputs_embeds': inputs_embeds}
1328
+ else:
1329
+ model_inputs = {'input_ids': input_ids}
1330
+
1331
+ model_inputs.update(
1332
+ {
1333
+ 'position_ids': position_ids,
1334
+ 'past_key_values': past_key_values,
1335
+ 'use_cache': kwargs.get('use_cache'),
1336
+ 'attention_mask': attention_mask,
1337
+ }
1338
+ )
1339
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
1340
+ for key, value in kwargs.items():
1341
+ if key not in model_inputs:
1342
+ model_inputs[key] = value
1343
+ return model_inputs
1344
+
1345
+ @staticmethod
1346
+ def _reorder_cache(past_key_values, beam_idx):
1347
+ reordered_past = ()
1348
+ for layer_past in past_key_values:
1349
+ reordered_past += (
1350
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1351
+ )
1352
+ return reordered_past
1353
+
1354
+ @torch.inference_mode()
1355
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = 'user',
1356
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1357
+ **kwargs):
1358
+ if history is None:
1359
+ history = []
1360
+ if logits_processor:
1361
+ gen_kwargs = {
1362
+ 'max_length': max_length,
1363
+ 'num_beams': num_beams,
1364
+ 'do_sample': do_sample,
1365
+ 'top_p': top_p,
1366
+ 'temperature': temperature,
1367
+ 'logits_processor': logits_processor,
1368
+ **kwargs
1369
+ }
1370
+ else:
1371
+ gen_kwargs = {
1372
+ 'max_length': max_length,
1373
+ 'num_beams': num_beams,
1374
+ 'do_sample': do_sample,
1375
+ 'top_p': top_p,
1376
+ 'temperature': temperature,
1377
+ 'logits_processor': logits_processor,
1378
+ **kwargs
1379
+ }
1380
+
1381
+ history.append({'role': role, 'content': query})
1382
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1383
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1384
+ outputs = self.generate(**inputs, **gen_kwargs)
1385
+ outputs = outputs.tolist()[0][len(inputs['input_ids'][0]):-1]
1386
+ response = tokenizer.decode(outputs)
1387
+ pattern = re.compile(r'.*?(?=<AI>|<用户>)', re.DOTALL)
1388
+ matches = pattern.findall(response)
1389
+ if len(matches) > 0:
1390
+ response = matches[0]
1391
+ history.append({'role': 'assistant', 'content': response})
1392
+ return response, history
1393
+
1394
+
1395
+ @add_start_docstrings(
1396
+ """
1397
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1398
+
1399
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1400
+ (e.g. GPT-2) do.
1401
+
1402
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1403
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1404
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1405
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1406
+ each row of the batch).
1407
+ """,
1408
+ MINICPM_START_DOCSTRING,
1409
+ )
1410
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1411
+ def __init__(self, config):
1412
+ super().__init__(config)
1413
+ self.num_labels = config.num_labels
1414
+ self.model = MiniCPMModel(config)
1415
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1416
+
1417
+ # Initialize weights and apply final processing
1418
+ self.post_init()
1419
+
1420
+ def get_input_embeddings(self):
1421
+ return self.model.embed_tokens
1422
+
1423
+ def set_input_embeddings(self, value):
1424
+ self.model.embed_tokens = value
1425
+
1426
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1427
+ def forward(
1428
+ self,
1429
+ input_ids: torch.LongTensor = None,
1430
+ attention_mask: Optional[torch.Tensor] = None,
1431
+ position_ids: Optional[torch.LongTensor] = None,
1432
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1433
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1434
+ labels: Optional[torch.LongTensor] = None,
1435
+ use_cache: Optional[bool] = None,
1436
+ output_attentions: Optional[bool] = None,
1437
+ output_hidden_states: Optional[bool] = None,
1438
+ return_dict: Optional[bool] = None,
1439
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1440
+ r"""
1441
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1442
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1443
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1444
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1445
+ """
1446
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1447
+
1448
+ transformer_outputs = self.model(
1449
+ input_ids,
1450
+ attention_mask=attention_mask,
1451
+ position_ids=position_ids,
1452
+ past_key_values=past_key_values,
1453
+ inputs_embeds=inputs_embeds,
1454
+ use_cache=use_cache,
1455
+ output_attentions=output_attentions,
1456
+ output_hidden_states=output_hidden_states,
1457
+ return_dict=return_dict,
1458
+ )
1459
+ hidden_states = transformer_outputs[0]
1460
+ logits = self.score(hidden_states)
1461
+
1462
+ if input_ids is not None:
1463
+ batch_size = input_ids.shape[0]
1464
+ else:
1465
+ batch_size = inputs_embeds.shape[0]
1466
+
1467
+ if self.config.pad_token_id is None and batch_size != 1:
1468
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1469
+ if self.config.pad_token_id is None:
1470
+ sequence_lengths = -1
1471
+ else:
1472
+ if input_ids is not None:
1473
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1474
+ logits.device
1475
+ )
1476
+ else:
1477
+ sequence_lengths = -1
1478
+
1479
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1480
+
1481
+ loss = None
1482
+ if labels is not None:
1483
+ labels = labels.to(logits.device)
1484
+ if self.config.problem_type is None:
1485
+ if self.num_labels == 1:
1486
+ self.config.problem_type = 'regression'
1487
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1488
+ self.config.problem_type = 'single_label_classification'
1489
+ else:
1490
+ self.config.problem_type = 'multi_label_classification'
1491
+
1492
+ if self.config.problem_type == 'regression':
1493
+ loss_fct = MSELoss()
1494
+ if self.num_labels == 1:
1495
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1496
+ else:
1497
+ loss = loss_fct(pooled_logits, labels)
1498
+ elif self.config.problem_type == 'single_label_classification':
1499
+ loss_fct = CrossEntropyLoss()
1500
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1501
+ elif self.config.problem_type == 'multi_label_classification':
1502
+ loss_fct = BCEWithLogitsLoss()
1503
+ loss = loss_fct(pooled_logits, labels)
1504
+ if not return_dict:
1505
+ output = (pooled_logits,) + transformer_outputs[1:]
1506
+ return ((loss,) + output) if loss is not None else output
1507
+
1508
+ return SequenceClassifierOutputWithPast(
1509
+ loss=loss,
1510
+ logits=pooled_logits,
1511
+ past_key_values=transformer_outputs.past_key_values,
1512
+ hidden_states=transformer_outputs.hidden_states,
1513
+ attentions=transformer_outputs.attentions,
1514
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_end|>",
4
+ "<|im_start|>",
5
+ "<|tool_call|>",
6
+ "<|execute_start|>",
7
+ "<|execute_end|>",
8
+ "<|fim_prefix|>",
9
+ "<|fim_middle|>",
10
+ "<|fim_suffix|>"
11
+ ],
12
+ "bos_token": {
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "eos_token": {
20
+ "content": "<|im_end|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "unk_token": {
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
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:bb74d51116831c3bf65db812c553f94ab0c88dcf97a5bbb37e3504f6d359c530
3
+ size 1181204
tokenizer_config.json ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "73440": {
31
+ "content": "<|im_end|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "73441": {
39
+ "content": "<|im_start|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "73442": {
47
+ "content": "<|tool_call|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "73443": {
55
+ "content": "<|execute_start|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "73444": {
63
+ "content": "<|execute_end|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "73445": {
71
+ "content": "<|fim_prefix|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "73446": {
79
+ "content": "<|fim_middle|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "73447": {
87
+ "content": "<|fim_suffix|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ }
94
+ },
95
+ "additional_special_tokens": [
96
+ "<|im_end|>",
97
+ "<|im_start|>",
98
+ "<|tool_call|>",
99
+ "<|execute_start|>",
100
+ "<|execute_end|>",
101
+ "<|fim_prefix|>",
102
+ "<|fim_middle|>",
103
+ "<|fim_suffix|>"
104
+ ],
105
+ "bos_token": "<s>",
106
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
107
+ "clean_up_tokenization_spaces": false,
108
+ "eos_token": "<|im_end|>",
109
+ "legacy": true,
110
+ "model_max_length": 1000000000000000019884624838656,
111
+ "pad_token": null,
112
+ "sp_model_kwargs": {},
113
+ "spaces_between_special_tokens": false,
114
+ "tokenizer_class": "LlamaTokenizer",
115
+ "unk_token": "<unk>",
116
+ "use_default_system_prompt": false
117
+ }